我正在尝试使用sf:form来持久化实体。
这是jsp:
<sf:form method="POST" action="${pageContext.request.contextPath}/addStudent" modelAttribute="student">
<fieldset>
<table>
<tr>
<th><sf:label path="nb">Number:</sf:label></th>
<td><sf:input type="text" path="nb"/><br/>
<sf:errors path="nb"></sf:errors>
</tr>
......
</table>
</fieldset>
实体中的属性是这样的:
@NotNull(message="not null")
@Size(min=5, max=10, message="length min 5")
@Column(name="NB", unique=true)
private String nb;
控制器:
@RequestMapping(value="/addStudent", method=RequestMethod.POST)
public ModelAndView addStudent(HttpServletRequest request, @ModelAttribute("student") @Valid Student student, BindingResult bR){
ModelAndView mav = new ModelAndView("students");
if(bR.hasErrors()){
return mav;
}
studentService.saveStudent(student);
return mav;
}
好吧,当我将nb字段留空或者条目变短时,我得到验证错误。我的问题是jsp中没有显示错误,但抛出异常:
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='length min 5', propertyPath=nb, rootBeanClass=class i.have.serious.problem.Student, messageTemplate='length min 5'}
javax.validation.ConstraintViolationException: Validation failed for classes [i.have.serious.problem.Student] during persist time for groups [javax.validation.groups.Default, ]
也许我想念一些东西......我感谢任何提示或帮助,thx
----------------------------- 已解决 ------- ----------------------------
答案 0 :(得分:1)
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:annotation-driven />
现在工作正常:) .. thx for careing tho!
答案 1 :(得分:0)
您正在方法中创建一个新的ModelAndView,这可能无法将bindingResult带回视图。
您可以将ModelAndView
作为附加参数,看看是否有效:
@RequestMapping(value="/addStudent", method=RequestMethod.POST)
public ModelAndView neuStudent(HttpServletRequest request, @ModelAttribute("student") @Valid Student student, BindingResult bR, ModelAndView mav){
mav.setViewName("students");
if(bR.hasErrors()){
return mav;
}
studentService.saveStudent(student);
return mav;
}