2012-08-04 74 views
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, ] 

也許我錯過了什麼。我明白任何提示或幫助,THX

------ -----------------------已解決------------------------ -----------

回答

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; 
} 
+0

thx關懷!問題解決,如下所述:)不過! – user1386375 2012-08-04 01:20:13

1

確實很好。我錯過了什麼 - >支持與驗證@Valid輸入@Controller,如果一個JSR- 303提供程序存在於類路徑中。

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護理壽!