0

我正在尝试使用 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, ]

也许我错过了一些东西..我感谢任何提示或帮助,谢谢

-----------------------------已解决-------- ---------------

4

2 回答 2

1

确实……我错过了一些东西->如果类路径上存在JSR-303 Provider,则支持使用@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 />

现在工作正常:) .. 感谢您的关心!

于 2012-08-04T01:21:49.000 回答
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;
}
于 2012-08-04T01:02:13.053 回答