简体   繁体   English

Spring MVC 如何从 Model 获取数据,为什么每次提交表单后都会创建 modelAttribute object?

[英]How Spring MVC getting data from Model and why is modelAttribute object created everytime after submitting form?

Everytime I submit form with errors processForm() method is called, errors are checked, BindingResult hasErrors() is true and I return customer-form which have error message next to wrong inputs, but before all that new Customer is always created and setters are called.每次我提交带有错误的表单时都会调用 processForm() 方法,检查错误,BindingResult hasErrors() 为真,并且我返回在错误输入旁边有错误消息的客户表单,但在始终创建新客户和设置器之前叫。 Why Spring creating new Customer object everytime I submit form and how long Spring keep customer data?为什么 Spring 每次我提交表格时都会创建新客户 object 以及 Spring 保留客户数据多长时间? Also, why my form inputs become empty if I mark url in browser and hit enter?另外,如果我在浏览器中标记 url 并按回车,为什么我的表单输入变为空?

I have form:我有形式:

<form:form action="processForm" modelAttribute="customer">
    First name: <form:input path="firstName" />
    <form:errors path="firstName" cssClass="error" />
    <br><br>
    Last name (*): <form:input path="lastName" />
    <form:errors path="lastName" cssClass="error" />
    <br><br>
    <input type="submit" value="Submit" />
</form:form>

and Controllers:和控制器:

    @RequestMapping("/showForm")
    public String showForm(Model theModel) {
        theModel.addAttribute("customer", new Customer());
        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(
            @ModelAttribute("customer") @Valid Customer theCustomer,
            BindingResult theBindingResult) {
       if (theBindingResult.hasErrors()) return "customer-form";
        return "customer-confirmation";
    }

Why Spring creating new Customer object everytime I submit form and how long Spring keep customer data?为什么 Spring 每次我提交表格时都会创建新客户 object 以及 Spring 保留客户数据多长时间?

Generally speaking, Spring is not creating new Customer object every time you submit the form.一般来说,Spring 不会在您每次提交表单时创建新Customer object。 It is binding form data to the model object that you sent from the GET handler:它将表单数据绑定到您从GET处理程序发送的 model object :

theModel.addAttribute("customer", new Customer());

And in the POST handler, the same object is being resolved withPOST处理程序中,相同的 object 正在解决

@ModelAttribute("customer") @Valid Customer theCustomer,

See how this resolution is done with @ModelAttribute in Spring Framework Documentation.在 Spring 框架文档中查看如何使用@ModelAttribute完成此解决方案。

The data will normally live through the requests if not configured otherwise, for example with @SessionAttributes .如果未配置其他方式,例如使用@SessionAttributes ,数据通常会在请求中存活。

Also, why my form inputs become empty if I mark url in browser and hit enter?另外,如果我在浏览器中标记 url 并按回车,为什么我的表单输入变为空?

This is a new GET request, ie, it's all the same as the first time you enter the URL and press enter!这是一个新的GET请求,即和第一次输入URL并回车一样!

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

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