简体   繁体   English

Spring表单commandName =会话属性

[英]Spring form commandName = session attribute

I have many pages with the same form where I bind my object using commandName. 我有许多页面具有相同的形式,在这些页面中我使用commandName绑定对象。 I try to put the object to session with name "myObject" and use it for form (commandName = "myObject"). 我尝试将对象放入名称为“ myObject”的会话中,并将其用于表单(commandName =“ myObject”)。 But system throws exception (Neither BindingResult nor plain target object for bean name "myObject"). 但是系统会引发异常(Bean名称“ myObject”的BindingResult和普通目标对象都不会)。 How can I bind the object to session for any controllers and requests? 如何将对象绑定到任何控制器和请求的会话?

That error is typical when your use a form:form tag that targets a command object that is not available in the request. 当您使用针对请求中不可用的命令对象的form:form标记时,通常会发生该错误。

A good approach is to combine @ModelAttribute annotated method with @SessionAttributes on a Controller that intially forwards to the view that contains the form, something like 一种好的方法是将@ModelAttribute注释的方法与@SessionAttributes在Controller上,该Controller最初转发到包含表单的视图,例如

@Controller
@SessionAttributes("myObject")
public class FormController {

    @ModelAttribute("myObject")
    public MyObject createMyObjectBean() {
        return new MyObject();
    }
    ...
}

The initally createMyObjectBean will be called with whatever is the first request to the controller methods, but it won't be called on subsequent request as the myObject value will come from session due to @SessionAttributes 最初的createMyObjectBean将以对控制器方法的第一个请求createMyObjectBean ,但是由于后续的myObject值将由于@SessionAttributes而来自会话,因此不会在后续请求中被调用

just note that for this approach to work, you must have a controller that forwards to the view that contains your form 只需注意,要使此方法起作用,您必须具有一个控制器,该控制器可以转发到包含表单的视图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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