Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is @ModelAttribute in Spring MVC?

    • 0
    • 2
    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 1.19k
    Comment on it

    @ModelAttribute implies to a property of the Model object in Spring MVC. This annotation workes only if your calss is Controller class i.e. declares with @Controller annotation.

    It is also used to define the command object that we declared by commandname attribute in our jsp file that would be bound with the HTTP request data

    We can apply @ModelAttribute on both methods as well as parameters of method. @ModelAttribute accepts an optional "value", which indicates the name of the attribute. If no value is provided to the annotation, then the value would be defaulted to the return type name in case of methods and parameter type name in case of method-parameters.

    For example you have a form object "UserModel" then Spring MVC pass this object to Controller method by using the @ModelAttribute annotation:

         @Controller  
            public class RegistrationController {  
    
            @Autowired 
            IUserService userService;
    
            @RequestMapping(value = "/userRegistrationForm", method = RequestMethod.GET)
            public ModelAndView userRegistrationForm(HttpServletRequest request, HttpServletResponse response)
            {
    
                logger.debug("Inside userRegistrationForm Action");
                ModelAndView modelAndView = null;
                UserModel sessionUser = (UserModel) request.getSession().getAttribute(
                        "user");
    
                logger.debug("UserID  : " + sessionUser.getEmailId());
                modelAndView = new ModelAndView("createUser");
                modelAndView.addObject("ownerId", sessionUser.getUserId());
                modelAndView.addObject("sessionUser", sessionUser);
                modelAndView.addObject("userFormBean", new UserModel());
                return modelAndView;
            }
    
            @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
            @ResponseBody
            public UserResponse registerUser(HttpServletRequest request,
                    @ModelAttribute("userFormBean") UserModel userFormBean)
            {
    
                logger.debug("Inside saveUser");
                return userService.saveUser(userFormBean);
            }
      }
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: