Java 我是Spring框架的初学者。我在项目中尝试自定义表单验证注释,但自定义验证注释无法工作

Java 我是Spring框架的初学者。我在项目中尝试自定义表单验证注释,但自定义验证注释无法工作,java,html,spring,validation,jsp,Java,Html,Spring,Validation,Jsp,FormValidationController.java package com.binod.formvalidation; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.sp

FormValidationController.java

package com.binod.formvalidation;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; 
import org.springframework.validation.BindingResult; 
import org.springframework.validation.annotation.Validated; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.servlet.ModelAndView;
import com.binod.formvalidation.Entity.Student;

@Controller
public class FormValidationController {

    @RequestMapping(value="/form.html" ,method=RequestMethod.GET)
    ModelAndView sendLoginForm()   { 
    ModelAndView andView=new ModelAndView("AdmissionForm");         
    return andView; 
            }    


    @ModelAttribute     
    public void addCommonError(Model model) {       
    model.addAttribute("commonError", "Welcome Spring MVC Zone");   }

    @RequestMapping(value="/submit.html", method=RequestMethod.POST)
    ModelAndView sendSuccessForm(@Valid @ModelAttribute("student")
     Student student, BindingResult bindingResult) {

    if(bindingResult.hasErrors()) {     
    ModelAndView andView=new ModelAndView("AdmissionForm");             
     return andView; 
        }       
    ModelAndView andView=new ModelAndView("AdmissionSuccess");
    return andView;
    }   

 }
自定义表单验证批注为
IsValidHobby.java

package com.binod.formvalidation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target;
import javax.validation.Constraint;
import org.springframework.messaging.handler.annotation.Payload;

@Documented 
@Constraint(validatedBy=HobbyValidator.class)
@Target({ElementType.FIELD}) 
@Retention(RetentionPolicy.RUNTIME)
public @interface IsValidHobby  {   
String message() default "Please provide a valid hobby accepted 
hobbies are football, volleyball,cricket"; 
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default{};     
}
package com.binod.formvalidation;  
import javax.validation.ConstraintValidator; 
import javax.validation.ConstraintValidatorContext;

public class HobbyValidator implements 
ConstraintValidator<IsValidHobby, String>  {

@Override   public void initialize(IsValidHobby iSvalidHobby) {         

            }

@Override   public boolean isValid(String studentHobby,
ConstraintValidatorContext ctx) {   
if(studentHobby==null) { 
return false; 
}
 if (studentHobby.matches("cricket|volleyBall|football")) {             
      return true;
        }
        else { 
     return false;
        }
    }

}
Student.java

package com.binod.formvalidation.Entity;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.sun.istack.internal.NotNull;

public class Student {
    @Size(min=4,max=9) 
    private String firstName;   
    private String lastName; 
    @NotNull
    private int rollNo;
    private StudentDetail studentDetail;


public String getFirstName() {  
return firstName;   }

 public StudentDetail getStudentDetail() {  
    return studentDetail;
        }
    public void setStudentDetail(StudentDetail studentDetail) {
    this.studentDetail = studentDetail;     
           }
    public void setFirstName(String firstName) {    
    this.firstName = firstName;
    }

    public String getLastName() {   
    return lastName;
      }

public void setLastName(String lastName) {  
this.lastName = lastName;
 }

public int getRollNo() {
return rollNo;
}

public void setRollNo(int rollNo) {         
this.rollNo = rollNo; 
}

}
StudentDetail.java

package com.binod.formvalidation.Entity;
import com.binod.formvalidation.IsValidHobby; 
import com.sun.istack.internal.NotNull;

public class StudentDetail {    
 @IsValidHobby
  private String studentHobby;   
 @NotNull   private String faculty,address;
 @NotNull
 private long phoneNo; 

 public String getStudentHobby() {      
 return studentHobby;
  }

 public void setStudentHobby(String studentHobby) {
 this.studentHobby = studentHobby;  
  }      
 public String getFaculty() {   
 return faculty;    
  } 
 public void setFaculty(String faculty) {
        this.faculty = faculty;     
  } 
 public String getAddress() {   
    return address;
    } 
 public void setAddress(String address) {   
 this.address = address; 
 } 
public long getPhoneNo() {      
return phoneNo;     
 }
public void setPhoneNo(long phoneNo) {  
this.phoneNo = phoneNo;     }
     }
AdmissionForm.jsp

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form%>
   <html>
    <head>
       <title>Admission Form</title> </head>
       <body> 
        <form:errors path="student.*"/>
        <h1 align="center">Student Submission Form</h1>   <br/><br/>
        <h2 align="center">${commonError}</h2>
            <form action="submit.html" method="POST">
            <table align="center"> 
            <tr> 
               <td>First Name</td> 
               <td><input type="text" name="firstName" />       
           </tr>    
           <tr>
               <td>Last Name</td>
                <td><input type="text" name="lastName" />    
           </tr>
           <tr>
              <td>Faculty</td>
              <td><input type="text" name="studentDetail.faculty" />        
           </tr>    
           <tr> 
              <td>RollNo</td>
              <td><input type="text" name="rollNo" /> 
            </tr> 
            <tr>
                <td>Phone NO</td>
                <td><input type="text" name="StudentDetail.phoneNo" />      
            </tr>
            <tr> 
                <td>Address</td>
                <td><input type="text" name="studentDetail.address" />      
            </tr>
            <tr>
                <td>Student Hobby</td>
                <td><input type="text" name="studentDetail.studentHobby"/>      
            </tr>   
             <tr > 
                 <td colspan="2" align="center">
                   <input type="submit" value="Submit" />
                 </td>  
            </tr>

         </table> 
      </form>
     </body> 
    </html>

按预期工作。在
studentDetail
字段上没有
@Valid
,因此验证不会传播。这在JSR-303验证文档中都有解释(基本上与Spring验证无关)。@M.Deinum只是试图告诉您将
@Valid
添加到student的
private StudentDetail StudentDetail
字段中。顺便说一句,当要验证的值为空时,验证程序通常返回
true
。谢谢@M.Deinum我的代码工作正常。在
studentDetail
字段上没有
@Valid
,因此验证不会传播。这在JSR-303验证文档中都有解释(基本上与Spring验证无关)。@M.Deinum只是试图告诉您将
@Valid
添加到student的
private StudentDetail StudentDetail
字段中。顺便说一句,当要验证的值为null时,验证程序通常返回
true
。谢谢@M.Deinum我的代码工作
<html>
  <head>
     <title>Admission Success</title>
  </head> 
 <body>
   <h1 align="center">Your Detail information!!!</h1>
    <table align="center">
      <tr>
        <td>First Name:</td> 
        <td>${student.firstName }</td>
      </tr>
      <tr> 
        <td>Last Name:</td> 
        <td>${student.lastName }</td>
       </tr> 
       <tr> 
         <td>Roll No:</td>  
         <td>${student.rollNo }</td>
        </tr>
        <tr>
          <td>Address:</td>
          <td>${student.studentDetail.address }</td>    
        </tr>
        <tr>
            <td>Faculty :</td>          
            <td>${student.studentDetail.faculty}</td>
        </tr> 
        <tr>        
           <td>PhoneNo:</td>
           <td>${student.studentDetail.phoneNo }</td>   
        </tr>
        <tr>
            <td>Student HObby</td>
            <td>${student.studentDetail.studentHobby}</td>
         </tr>
    </table>
 </body> 
<?xml version="1.0" encoding="UTF-8"?> <beans 
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

   <context:component-scan base-package="com.binod.formvalidation" />
   <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/studentMessage" />
    </bean>
   </beans>