来源:http://blog.csdn.net/xiejx618/article/details/43638537###;
参考资料:spring-framework-reference的Using @ModelAttribute on a method和Using @ModelAttribute on a method argument
先看一个没有使用@ModelAttribute的Controller方法.
- @RequestMapping("/save")
- public String save(User user) {
- user.setUsername("U love me");
- userService.save(user);
- return "result";
- }
执行此方法时会将key为"user"(注意:这里即使参数名称是user1,key一样还是"user"),value为user的对象加入到model.在jsp页面可以通过${user.id}和${user.name}得到值的,即上面方法和下面方法是相当的.
- @RequestMapping("/save")
- public String save(Model model,int id,String username) {
- User user=new User();
- //这里是通过反射从request里面拿值再set到user
- user.setId(id);
- user.setUsername(username);
- model.addAttribute("user",user);
- user.setUsername("U love me");
- userService.save(user);
- return "result";
- }
1.在方法上使用@ModelAttribute
- @ModelAttribute("user1")
- public User addUser(User user) {
- return new User(520,"I love U");
- }
2.在方法参数上使用@ModelAttribute.
- @RequestMapping("/save")
- public String save(@ModelAttribute User user) {
- user.setUsername("U love me");
- userService.save(user);
- return "result";
- }
使用了@ModelAttribute可修改这个key,不一定是"user",此情况下,用与不用@ModelAttribute没有区别.
3.再来看看在方法和方法参数上结合使用@ModelAttribute,即上面两步的两个方法都添加UserController,如下:
- @ModelAttribute("user1")
- public User addUser(User user) {
- return new User(520,"I love U");
- }
- @RequestMapping("/save")
- public String save(@ModelAttribute User user) {
- user.setUsername("U love me");
- userService.save(user);
- return "result";
- }
再来个小小假设,将上面@ModelAttribute("user1")的user1改为user,其它不变.虽然执行了addUser方法,那么执行到save方法内,user对象的字段值还是来源于请求,最后返回到jsp页面,model里也只有一个User类型对象.
4.另类:
- @ModelAttribute
- @RequestMapping("/save")
- public String save(@ModelAttribute User user) {
- user.setUsername("U love me");
- userService.save(user);
- return "result";
- }
二.下面再看看结合@SessionAttributes的用法.
1.先看看这段代码
- @Controller
- @RequestMapping("user")
- @SessionAttributes("test")
- public class UserController {
- @RequestMapping(value = "test1")
- public String test1(Map<String, Object> model, SessionStatus sessionStatus) {
- model.put("test","something");
- //sessionStatus.setComplete();
- return "user/list";
- }
- @RequestMapping(value = "test2")
- public String test2(Map<String,?> model) {
- Object test = model.get("test");
- System.out.println(test);
- return "user/list";
- }
- }
2.再看结合@ModelAttribute的用法.
- @Controller
- @RequestMapping("user")
- @SessionAttributes("test")
- public class UserController {
- @RequestMapping(value = "test1")
- public String test1(HttpServletRequest request) {
- User user = new User("xiejx618");
- request.getSession().setAttribute("test",user);
- return "user/list";
- }
- @RequestMapping(value = "test2")
- public String test2(@ModelAttribute("test") User user,SessionStatus sessionStatus) {
- System.out.println(user.getUsername());
- sessionStatus.setComplete();
- return "user/list";
- }
- }
我个人很少这样用,用原始的写法就清晰很多了,但要看明白别人写的代码。