简体   繁体   中英

Spring MVC how to forbid data binding to ModelAttribute?

I have a simple @Controller class that renders a page after user has logged in:

@Controller
@SessionAttributes("user")
public class DashBoardController {

    @RequestMapping(value="/user/dashBoard", method=RequestMethod.GET)
    public String showDashBoardPage(@ModelAttribute("user") User user, Model model) {
        //do some work here....
        return "dashBoard";
    }

}

as you see, user attribute is already present in session and by using @ModelAttribute annotation I only want to pull it from there, nothing else. But if you add any parameter to request, then spring tries to bind this parameter to existing user object, which is not what I want, how to forbid this behavior?

To be more specific, here's the User class:

public class User {

   private String name;
   private String password;
   private Language language;

   //public getters and setters here...
} 

If I want to change language of my dashBoard page, I request this page with addition of ?language=en parameter and in this case Spring tries to change language field of user model attribute, which of course fails with type mismatch exception. Of course I can walk around by changing parameter name to something that doesn't match any of User fields, but that seems like a fragile solution. Is there any way to control this data binding behavior? I use Spring 4.1.3

There is an attribute of @ModelAttribute called binding which you can set to false to disable binding of request parameters. Usage: @ModelAttribute(binding=false) before method parameter.

Reference: click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM