I am new to Spring. The problem I have is that my form is not populated with its original values when returning from validation. The reason why I implement the Validator interface (instead of using validation annotation) is because I check the DB for the existence of the username. Here is my code (html tags omitted).
JSP:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<form:form action="register.html" commandName="userCommand" method="POST">
<form:errors path="*" cssClass="redBold"/>
Username:
<form:input path="username"/><form:errors path="username" cssClass="error" />
Password:
<form:password path="password"/>
Retype password:
<form:password path="password2"/>
Sex:
<form:radiobutton path="sex" value="F" label="Female"/>
<form:radiobutton path="sex" value="M" label="Male"/>
Date of birth:
<form:select path="dobDay" items="${dobDays}"/>
<form:select path="dobMonth" items="${dobMonths}"/>
<form:select path="dobYear" items="${dobYears}"/>
Postcode:
<form:input path="postcode"/>
<input type="submit" value="Register" class="button"/>
</form:form>
Controller:
@Controller
@RequestMapping("/register.*")
public class UserRegistrationController {
@RequestMapping(method = RequestMethod.POST)
public ModelAndView submitForm(HttpServletRequest request, @ModelAttribute("userCommand") User user, BindingResult result) throws Exception {
UserRegistrationValidator validator = new UserRegistrationValidator();
validator.validate(user, result);
if(result.hasErrors()){
// when returning from here I dont see values in the JSP form
return new ModelAndView("redirect:/registe开发者_运维技巧r.html","userCommand",user);
}
// more code
return new ModelAndView("redirect:/home.html");
}
}
Validator:
@Component
public class UserRegistrationValidator implements Validator {
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Override
public boolean supports(Class clazz) {
return User.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors error) {
User user = (User) obj;
ValidationUtils.rejectIfEmpty(error, "username", "mandatory");
if (userService.exists(user.getUsername()){
error.rejectValue("username", null, "*");
}
if (user.getPostcode() == null || "".equals(user.getPostcode().toString())){
error.rejectValue("postcode", null, "*");
}
}
}
Thanks a lot!
as long as you use redirect, the userCommand will not passed to redirected url.
do not try to redirect when submitted command is not valid
return new ModelAndView("register.html","userCommand",user);
or maybe you can save the userCommand to session if you still want use redirect, But I Think it's not a good practice
精彩评论