I have a controller with the following methods:
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Model model) {
model.addAttribute("user", new User());
return "register";
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("user") User user, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
UserValidator validator = new UserValidator();
validator.validate(user, bindingResult);
if (bindingResult.hasErrors()) {
redirectAttributes.addFlashAttribute(BindingResult.MODEL_KEY_PREFIX + "user", bindingResult);
redirectAttributes.addFlashAttribute("user", user);
return "redirect:/register";
}
...
}
My jsp:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form method="POST" modelAttribute="user" action="/registration">
<div>
<label>First Name</label>
<form:input path="firstName"/>
<form:errors path="firstName"/>
</div>
<div>
<label>Last Name</label>
<form:input path="lastName"/>
<form:errors path="lastName"/>
</div>
<div>
<label>E-mail</label>
<form:input path="email"/>
<form:errors path="email"/>
</div>
<div>
<label>Password</label>
<form:password path="password"/>
<form:errors path="password"/>
</div>
<input type="submit" value="Submit"/>
</form:form>
However, if there are errors they are not shown after the redirect because I create a new user every time the /register is called. Is there a way to fix this without storing the user in a session?
I can create another method just for this case so I can redirect to /register2 without losing the user:
@RequestMapping(value = "/register2", method = RequestMethod.GET)
public String register2() {
return "register";
}
It worked like I wanted, but it's a very bad approach.
/registerinstead of/registration? You don't want to show registration in the address bar but you don't mind showing register2?