Spring MVC如何禁止数据绑定到ModelAttribute? [英] Spring MVC how to forbid data binding to ModelAttribute?

查看:203
本文介绍了Spring MVC如何禁止数据绑定到ModelAttribute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 @Controller 类,在用户登录后呈现页面:

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";
    }

}

如你所见, user 属性已存在于会话中,并且使用 @ModelAttribute 注释我只想从那里拉出来,没有别的。但是如果你添加任何参数来请求,那么spring会尝试将这个参数绑定到现有的用户对象,这不是我想要的,如何禁止这种行为?

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更具体地说,这是User类:

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...
} 

如果我想更改 dashBoard 页面的语言,我请求此页面添加?language = en 参数,在这种情况下,Spring尝试更改用户模型属性的语言字段,当然这会因类型不匹配异常而失败。
当然,我可以通过将参数名称更改为与用户字段中的任何一个不匹配的内容来处理,但这似乎是一个脆弱的解决方案。
有没有办法控制这种数据绑定行为?
我使用Spring 4.1.3

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

推荐答案

有一个属性为 @ModelAttribute 名为 binding ,您可以将其设置为false以禁用请求参数的绑定。用法: @ModelAttribute(binding = false)在方法参数之前。

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.

参考:点击

这篇关于Spring MVC如何禁止数据绑定到ModelAttribute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆