簡體   English   中英

使用Spring表單的驗證錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM