[英]Validation Error using Spring form
我正在尝试使用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, ]
也许我想念一些..我感谢任何提示或帮助,谢谢
-----------------------------解决了-------------------- ---------------
好吧,确实..我错过了一些事情->如果类路径中存在JSR-303提供程序,则支持使用@Valid验证@Controller输入。
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呵呵!
您正在方法中创建一个新的ModelAndView,这可能不会将bindingResult带回视图。
您是否可以将ModelAndView
用作附加参数,看看是否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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.