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. Why Spring creating new Customer object everytime I submit form and how long Spring keep customer data? Also, why my form inputs become empty if I mark url in browser and hit enter?
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?
Generally speaking, Spring is not creating new Customer
object every time you submit the form. It is binding form data to the model object that you sent from the GET
handler:
theModel.addAttribute("customer", new Customer());
And in the POST
handler, the same object is being resolved with
@ModelAttribute("customer") @Valid Customer theCustomer,
See how this resolution is done with @ModelAttribute
in Spring Framework Documentation.
The data will normally live through the requests if not configured otherwise, for example with @SessionAttributes
.
Also, why my form inputs become empty if I mark url in browser and hit enter?
This is a new GET
request, ie, it's all the same as the first time you enter the URL and press enter!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.