SpringBoot's summary of annotation @ModelAttribute

question

  The @ModelAttribute annotation accepts the json parameter passed by postman but cannot receive the value. In fact, I don’t know much about @ModelAttribute, so I just researched it!

 @RequestMapping("/test")
    public String test(@ModelAttribute("user") User user2) {
        System.out.println("user2"+JSON.toJSONString(user2));
        return "test";
    }

In this way, the JSON data passed in by postman cannot be received.

In fact, it is mainly due to insufficient understanding of the usage of @ModelAttribute.

The @ModelAttribute annotation can be used on methods and method parameters.

  1. Annotated on the method
    The method annotated by @ModelAttribute will be executed before each method of this controller is executed. So for the usage of one controller mapping multiple URLs, use it with caution.
  2. @ModelAttribute annotates the parameters of a method.
    There are two cases for annotating method parameters
    a. Obtained from the model, for example as follows:
      @ModelAttribute("user")
    public void addUser(@RequestBody User user, Model model) {
        System.out.println("ModelAttribute:"+1);
        model.addAttribute(user);
    }
    /**
     * test
     * @return string
     */
    @RequestMapping("/test")
    public String test(@ModelAttribute("user") User user2) {
        System.out.println("user2"+JSON.toJSONString(user2));
        return "test";
    }

Among them, addUser has another way of writing

   public User addUser(@RequestBody User user) {
       System.out.println("ModelAttribute:"+1);
       return user;
    }

In this example, @ModelAttribute("user") User user2 annotates the method parameter, and the value of the parameter user comes from the model attribute in the addUser() method.

b. Get it from the Form form or URL parameters (in fact, you can get the user object without this comment)

 @RequestMapping("/test")
    public String test(@ModelAttribute("user") User user2) {
        System.out.println("user2"+JSON.toJSONString(user2));
        return "test";
    }

Because the above problem is to receive data in JSON format, b cannot satisfy the situation. The solution I started thinking was to add @RequestBody
like below:

@RequestMapping("/test")
    public String test(@RequestBody @ModelAttribute("user") User user2) {
        System.out.println("user2"+JSON.toJSONString(user2));
        return "test";
 }

Then I found that it doesn't work at all, so I can only use a. Get it from the model!
So I have the following solution:

   public User addUser(@RequestBody User user) {
       System.out.println("ModelAttribute:"+1);
       return user;
    }

 @RequestMapping("/test")
    public String test(@RequestBody @ModelAttribute("user") User user2) {
        System.out.println("user2"+JSON.toJSONString(user2));
        return "test";
 }
 

Guess you like

Origin blog.csdn.net/Youning_Yim/article/details/115835737