如何防止spring mvc从请求中覆盖会话属性 [英] how do I prevent spring mvc overwriting sessionattributes from request

查看:303
本文介绍了如何防止spring mvc从请求中覆盖会话属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户登录的MVC Spring应用程序,它存储了一个User @ SessionAttribute,我随后会参考它。当在POST请求中更新Customer对象时,我希望将会话用户信息添加到此对象中。
我的问题是,当我访问客户POST中的@ModelAttribute(user)User对象时,spring已经将请求参数绑定到它中,即User.name具有来自提交表单的Customer.name的值。

注意,我所有的控制器都是我的AppController的子类,这是声明@SessionAttributes的地方。但是,如果它是一个单一的控制器,原则是一样的。



所以我可以防止弹簧绑定形式:客户名称值为User.name?



(我怀疑webflow会是一个更合适的框架,但现在没有时间用这个重写)$ b $您可以使用 @InitBinder 来允许或禁止绑定模型属性的某些字段:
$ $ $ $ $ $ $ $ $ $ $ $ $ $

$ b $ @ $ $ $ $ $ $


$ b $公共无效configureBindingOfUser(WebDataBinder联编程序){
binder.setAllowedFields() ; //没有允许的字段
}

然而,我认为这不是一个好主意使用 @SessionAttributes 来存储当前用户或其他类似的对象。 @SessionAttributes 最初设计用于维护 GET POST 请求,而不是通常用于访问会话的方式。

也许最好使用 session -scoped bean或自定义参数解析器来访问这类信息。

I have an MVC spring application where the user logs on, this stores a User @SessionAttribute , which I refer to subsequently e.g. when updating a Customer object in a POST request I want the session User info to add to this object. My problem is when I access the @ModelAttribute("user") User object in the customer POST, spring has bound request parameters into it i.e. the User.name has the value of the Customer.name from the submitted form.

NB I've kind of hacked this in that all controllers are subclasses of my AppController, which is where the @SessionAttributes are declared. But the principle would be the same if it was a single controller.

So can I prevent spring binding form:customer name value to User.name?

(I suspect webflow would be a more suitable framework for this, but don't have the time available right now to rewrite using this)

解决方案

You can allow or disallow binding of certain fields of your model attributes using @InitBinder:

@InitBinder("user")
public void configureBindingOfUser(WebDataBinder binder) {
    binder.setAllowedFields(); // No fields allowed
}

However, I don't think it's a good idea to use @SessionAttributes to store the current user or other similar objects. @SessionAttributes was originally designed to maintain state of form-backing objects between GET and POST requests, not as a general purpose way to access a session.

Perhaps it would be better to use session-scoped beans or custom argument resolvers to access this kind of information.

这篇关于如何防止spring mvc从请求中覆盖会话属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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