2015-01-29 7 views
0

Я новичок в Spring MVC. Мне нужно проверить форму с помощью тега <Spring:bind>. Но он не проверяет поля ввода. пожалуйста помогите.Валидация формы не работает весной MVC

Student.java

public class Student { 

    @Size(min=2,max=30) 
    private String studentName; 

    @NotNull 
    private String studentHobby; 

    public String getStudentName() { 
     return studentName; 
    } 
    public void setStudentName(String studentName) { 
     this.studentName = studentName; 
    } 
    public String getStudentHobby() { 
     return studentHobby; 
    } 
    public void setStudentHobby(String studentHobby) { 
     this.studentHobby = studentHobby; 
    } 
} 

StudentController.java

@Controller 
public class StudentController { 

    @RequestMapping(value="/admissionForm.html", method = RequestMethod.GET) 
    public ModelAndView getAdmissionForm() { 
     ModelAndView model = new ModelAndView("AdmissionForm"); 
     model.addObject("student1",new Student()); 
     return model; 
    } 

    @RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST) 
    public ModelAndView submitAdmissionForm(@Valid @ModelAttribute("student1") Student student1,BindingResult result) { 

     if (result.hasErrors()) { 
      ModelAndView model1 = new ModelAndView("AdmissionForm"); 
      return model1; 
     } 
     ModelAndView model = new ModelAndView("AdmissionSuccess"); 
     return model; 
    } 

} 

Спринг-диспетчерская-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans  
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 


    <context:component-scan base-package="com.ram.StudentController" /> 
    <mvc:annotation-driven/> 

    <bean id="viewResolver" 
     class="org.springframework.web.servlet.view.InternalResourceViewResolver" > 
     <property name="prefix"> 
      <value>/WEB-INF/</value> 
     </property> 
     <property name="suffix"> 
      <value>.jsp</value> 
     </property> 
</bean> 

<bean id="messageSource" 
     class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 

     <property name="basename" value="/WEB-INF/studentmessages" /> 
    </bean> 
</beans> 

AdmissionForm.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> 
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 
<html> 
<body> 
    <h1>User Registration</h1> 
    <form action="/FirstSpringMVCProject/submitAdmissionForm.html" 
     method="post"> 


     <spring:bind path="student1.studentName"> 
      <input value="${status.value}" name="${status.expression}"> 
     <c:if test="${status.error}"> 
      Error codes: 
      <c:forEach items="${status.errorMessages}" var="error"> 
       <c:out value="${error}"/> 
      </c:forEach> 
     </c:if> 

     </spring:bind> 
     <spring:bind path="student1.studentHobby"> 
      <input value="${status.value}" name="${status.expression}"> 
     <c:if test="${status.error}"> 
      Error codes: 
      <c:forEach items="${status.errorMessages}" var="error"> 
       <c:out value="${error}"/> 
      </c:forEach> 
     </c:if> 
     </spring:bind> 
<input type="submit" value="Submit this form by clicking here" /> 
    </form> 

</body> 
</html> 

studentmessages.properties

Size.student1.studentName = please enter a value for {0} field between {2} and {1} characters. 
NotNull.student1.studentHobby = HObby should not be Enmpty 

Вот пример кода. Заранее спасибо.

ответ

0

Связывание ошибки сохраняются внутри result.getModel(), но путем создания ModelAndView экземпляр вы разрушив эту модель, вы должны сделать, как ModelAndView("AdmissionForm", result.getModel());

@RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST) 
    public ModelAndView submitAdmissionForm(@Valid @ModelAttribute("student1") Student student1,BindingResult result) { 

     if (result.hasErrors()) { 
      ModelAndView model1 = new ModelAndView("AdmissionForm", result.getModel()); 
      return model1; 
     } 
     ModelAndView model = new ModelAndView("AdmissionSuccess"); 
     return model; 
    } 
+0

Я попробовал это, но это не работает. Он не показывает никаких ошибок, а не перенаправляется на страницу «AdmissionSucecess». –

Смежные вопросы