我对如何使用@SessionAttributes感到困惑

zon*_*ono 19 spring session-variables spring-mvc

我试图了解Spring MVC的架构.但是,我完全被@SessionAttributes的行为搞糊涂了.

请看下面的SampleController,它是由SuperForm类处理post方法.事实上,只是SuperForm类的字段只能像我预期的那样绑定.

但是,在我将@SessionAttributes放入Controller后,处理方法作为SubAForm进行绑定.任何人都可以解释我在这个绑定中发生了什么.

-------------------------------------------------------

@Controller
@SessionAttributes("form")
@RequestMapping(value = "/sample")
public class SampleController {

    @RequestMapping(method = RequestMethod.GET)
    public String getCreateForm(Model model) {
        model.addAttribute("form", new SubAForm());
        return "sample/input";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String register(@ModelAttribute("form") SuperForm form, Model model) {
        return "sample/input";
    }
}

-------------------------------------------------------

public class SuperForm {

    private Long superId;

    public Long getSuperId() {
        return superId;
    }

    public void setSuperId(Long superId) {
        this.superId = superId;
    }

}

-------------------------------------------------------

public class SubAForm extends SuperForm {

    private Long subAId;

    public Long getSubAId() {
        return subAId;
    }

    public void setSubAId(Long subAId) {
        this.subAId = subAId;
    }

}

-------------------------------------------------------

<form:form modelAttribute="form" method="post">
    <fieldset>
        <legend>SUPER FIELD</legend>
        <p>
            SUPER ID?<form:input path="superId" />
        </p>
    </fieldset>
    <fieldset>
        <legend>SUB A FIELD</legend>
        <p>
            SUB A ID?<form:input path="subAId" />
        </p>
    </fieldset>
    <p>
        <input type="submit" value="register" />
    </p>
</form:form>
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 24

处理POST请求时,Spring会执行以下操作:

  • 如果没有@SessionAttributes:Spring实例化一个新实例SuperForm(从签名中推断出类型register()),则通过表单字段中的值填充其属性并将其传递给register()方法.

  • 使用@SessionAttributes:Spring从会话中获取模型属性的实例(GET由于存在而在处理时放置它@SessionAttributes),通过from字段中的值更新其属性并将其传递给register()方法.

也就是说,使用@SessionAttributes,register()获取放置在Model中的模型属性对象的相同实例getCreateForm().