在学习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注解,
但是在这个例子里面产生的效果和不加似乎是一样的,都能够绑定表单信息到对象中,
所以想问下这个注解的功能?在这个例子中是不是即使不显示写也能有一样的功能?
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
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.
Although it has its own characteristics, I have never used it after using it for so long. I think it can be ignored @ModelAttribute