如何将操作参数绑定到 Spring MVC 3.x 中会话范围内存储的对象?
我想做这样的事情:
public ModelAndView someAction(SessionUser sessionUser, Model model) {
model.addAttribute(sessionUser);
return new ModelAndView("someview");
}
SessionUser 对象的实例存储在 Session 中,并在请求执行期间绑定到 sessionUser 参数。
我是 Spring MVC 的新手,但在 .NET MVC 中,这可以通过创建 ModelBinder 来完成:
public class SessionUserModelBinder : IModelBinder
{
private const string sessionUserSessionKey = "_sessionUser";
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Return the sessionUser from Session[] (creating it first if necessary)
SessionUser sessionUser = (SessionUser)controllerContext.HttpContext.Session[sessionUserSessionKey];
if (sessionUser == null)
{
sessionUser = new SessionUser();
controllerContext.HttpContext.Session[sessionUserSessionKey] = sessionUser;
}
return sessionUser;
}
}
这将作为请求执行管道的一部分执行。如果在请求参数中未找到 sessionUser,则会尝试此自定义模型绑定器。
Spring MVC 3 中是否有类似的机制可以让我完成同样的事情?我希望我的控制器及其方法不知道绑定的对象是否来自表单字段、url 参数、会话等。
提前致谢!
I would like to do something like this:
public ModelAndView someAction(SessionUser sessionUser, Model model) {
model.addAttribute(sessionUser);
return new ModelAndView("someview");
}
Where an instance of the SessionUser object is stored in the Session and is bound to the sessionUser parameter during the execution of the request.
I'm new to Spring MVC, but in .NET MVC this could be accomplished by creating a ModelBinder as such:
public class SessionUserModelBinder : IModelBinder
{
private const string sessionUserSessionKey = "_sessionUser";
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Return the sessionUser from Session[] (creating it first if necessary)
SessionUser sessionUser = (SessionUser)controllerContext.HttpContext.Session[sessionUserSessionKey];
if (sessionUser == null)
{
sessionUser = new SessionUser();
controllerContext.HttpContext.Session[sessionUserSessionKey] = sessionUser;
}
return sessionUser;
}
}
This would be executed as part of the request execution pipeline. If sessionUser wasn't found in the Request parameters, it would give this custom model binder a shot.
Is there a similar mechanism in Spring MVC 3 that would allow me to accomplish the same thing? I would prefer that my controller and its methods not know whether the bound object comes from form fields, url parameters, the session, etc.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以以声明方式将模型属性绑定到会话。为此,您需要使用
@SessionAttributes("sessionUser")
注释您的控制器。另请参阅:
Yes, you can declaratively bind a model attribute to the session. In order to do that you need to annotate your controller with
@SessionAttributes("sessionUser")
.See also: