Usage of SpringMvc @ModelAttribute

Reference: Spring 3.x Enterprise Application Development Practice Chapter 15: SpringMvc Page: 532

ModelAttribute is literally an attribute of the model.

The model data is the most important for the MVC framework, because the control (C) is to generate the model data (M), and the view (V) is to render the model data.

Spring Mvc provides multiple ways to output model data.

1.ModelAndView returns the ModelAndView object public ModelAndView request();

2. @ModeAttribute standardizes the annotation when entering the parameter, and the object entering the parameter will be placed in the data model. public String request(@ModelAttribute("user") User user);

3. Add such input parameters to Map and Model public String request(Model model,Map map);

4.@SessionAttribute

It can be seen from the above that the @ModelAttribute annotation is used to output model data. 

The first usage: add annotations when entering parameters

  @RequestMapping("testModelAttribute")
    public String testModelAttribute(@ModelAttribute("user") User user, ModelMap modelMap)
    {
        user.setUserName("mindong");
        modelMap.put("password",123456);
        return "test";
    }

Use ${user.userName}<br> ${password} on the test.jsp page to get user attributes and the attributes you set.

The second usage: add annotations before the method

  @RequestMapping("testModelAttribute")
    public String testModelAttribute(@ModelAttribute("user") User user, ModelMap modelMap) 1
    {
        user.setUserName("mindong");  
        modelMap.put("password",123456);
        return "test";
    }

    @ModelAttribute("user")
    public User initUser()
    {
        User user = new User();
        user.setUserId(1);
        user.setUserName("mindong");
        return user;
    }

When calling the testModelAttribute method, the initUser method that uses @ModelAttribute will be called first, and the return value will be added to the model. Since the @ModelAttribute of the InitUser method and the @ModelAttribute of the testModelAttribute method are the same, both are user.

This is that SpringMvc will first assign the attributes obtained in initUser to the user of testModelAttribute, and then overwrite the user according to the Http request parameters, so as to obtain an integrated version of the user object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855700&siteId=291194637