java - SpringMVC中的@ModelAttribute注解是可有可无的吗?
天蓬老师
天蓬老师 2017-04-18 10:53:45
0
3
585

在学习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注解,
但是在这个例子里面产生的效果和不加似乎是一样的,都能够绑定表单信息到对象中,
所以想问下这个注解的功能?在这个例子中是不是即使不显示写也能有一样的功能?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
洪涛

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!