Home  >  Q&A  >  body text

java - SpringMVC中的@ModelAttribute注解是可有可无的吗?

在学习SpringMVC中的使用Controller接受表单的值,
按照《Spring实战》中的代码,Controller如下:

    @RequestMapping(value = "/register", method = POST)
    public String processRegistration(Spitter spitter) {
        System.out.println(spitter.getUsername());
        spitterRepository.save(spitter);
        return "redirect:/spitter/" + spitter.getUsername();
    }

打印那行是我自己加的,用来验证表单的值是否绑定到了Spitter对象
而Spring官方的教程中在Spitter前面多了一个@ModelAttribute注解,
但是在这个例子里面产生的效果和不加似乎是一样的,都能够绑定表单信息到对象中,
所以想问下这个注解的功能?在这个例子中是不是即使不显示写也能有一样的功能?

天蓬老师天蓬老师2743 days ago586

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:55:45

    No, @ModelAttribute has two functions.
    One is to take out the data, that is, take the data out of the request and encapsulate it into the parameters of the controller method.
    The other is to place this data into the Model, so that you can use it in jsp Use EL expressions on the page to retrieve data and display it

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:55:45

    If the @ModelAttribute annotation is added to the parameter, the key in @ModelAttribute will be found first before executing @RequestMapping. If there is no @ModelAttribute and it is not available or not obtained, a spitter object will be instantiated through reflection and then obtained through request. to the value you set into the object. Although the result is the same, the process is different.

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:55:45

    Although it has its own characteristics, I have never used it after using it for so long. I think it can be ignored @ModelAttribute

    reply
    0
  • Cancelreply