我是Spring的新手。我遇到的问题是,从验证返回时,我的表单没有填充其原始值。我实现Validator接口(而不是使用验证注释)的原因是因为我检查DB是否存在用户名。这是我的代码(省略了html标签)。
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
@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:/register.html","userCommand",user);
}
// more code
return new ModelAndView("redirect:/home.html");
}
}
验证
@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, "*");
}
}
}
非常感谢!
答案 0 :(得分:2)
只要您使用重定向,userCommand就不会传递给重定向的网址。
当提交的命令无效时,不要尝试重定向
return new ModelAndView("register.html","userCommand",user);
或者你可以将userCommand保存到session,如果你仍然想要使用重定向,但我认为这不是一个好习惯