在Spring中绑定时保护特定字段 [英] Protect specific fields when binding in Spring

查看:315
本文介绍了在Spring中绑定时保护特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在允许用户编辑个人资料信息的页面上工作。我希望他们能够编辑他们的公共信息,但不允许他们更改系统标志,例如他们的用户类型。

I'm working on page that allows users to edit profile info. I want them to be able to edit their public info, but not allow them to change system flags such as their user type.

这是用Spring MVC(3.0)实现的。 User对象具有典型字段,例如 firstName lastName email (所有都应该是可编辑的)和布尔管理员(不应该是可编辑的。

This is implemented with Spring MVC (3.0). The User object has typical fields such as firstName, lastName, email (all should be editable) and a boolean administrator (which should not be editable.

我的方法看起来类似这样的事情:

My method looks something like this:

@RequestMapping(method = RequestMethod.POST)
public String doEdit(
        @ModelAttribute("user") User user,
        BindingResult result,
        ModelMap model)
throws IOException
{
      // validate, blah blah
      // save user object
      // return page

}

我的表格包括字段 firstName lastName 等,似乎工作正常。

My form includes fields firstName, lastName etc and seemed to work fine.

问题在于,如果恶意用户将参数 administrator 的查询发布为true,则可以在不应该设置此字段时设置该字段。

The problem is that if a malicious user posts a query with the parameter administrator as "true" they can set this field when they shouldn't.

我知道我可以用字段I创建一个单独的表单对象想要更改并使用它进行自动绑定。 (复制数据)。问题是我有很多地方使用这种技术。 (对于用户和其他对象)。当我想添加字段时,维护是一件麻烦事。

I know I can create a separate "form" object with just the fields I want to change and use that for the automatic binding. (the copy over the data). The problem is that I have a lot of places which use this technique. (for the user and other objects). It'd be a hassle to maintain when I want to add fields.

有没有办法在Spring MVC中使用注释或其他技术将参数列入白名单并防止更改任意域对象属性?

Is there a way to use annotations or other techniques in Spring MVC to whitelist parameters and prevent changes to arbitrary domain object properties?

推荐答案

DataBinder有两个名为 allowedFields 的属性和 disallowedFields 定义(dis)允许绑定的内容。只需在 @InitBinder 方法中使用它:

The DataBinder has two properties named allowedFields and disallowedFields that define what to (dis)allow for binding. Just use that in your @InitBinder method:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.setDisallowedFields("administrator");
}

这篇关于在Spring中绑定时保护特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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