📜  Spring MVC自定义验证

📅  最后修改于: 2020-12-04 08:46:37             🧑  作者: Mango

Spring MVC自定义验证

Spring MVC框架允许我们执行自定义验证。在这种情况下,我们声明自己的注释。我们可以根据自己的业务逻辑执行验证。

Spring MVC自定义验证示例

在此示例中,我们同时使用预定义的批注和自定义批注来验证用户输入。

1.将依赖项添加到pom.xml文件。

pom.xml



    org.springframework
    spring-webmvc
    5.1.1.RELEASE



    org.apache.tomcat
    tomcat-jasper
    9.0.12

    
  
    javax.servlet  
    servlet-api  
    3.0-alpha-1  



    javax.servlet
    jstl
    1.2

 

    org.hibernate.validator
    hibernate-validator
    6.0.13.Final

2.创建bean类

Employee.java

package com.javatpoint;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import com.javatpoint.customvalidation.Password;

public class Employee {
    private String name;
    //Custom annotation
    @Password
    private String password;
    //Predefined annotation
    @Min(value=18, message="must be equal or greater than 18")
    @Max(value=45, message="must be equal or less than 45")
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }    
}

3.创建控制器类

EmployeeController.java

 package com.javatpoint;

import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class EmployeeController {
    
    @RequestMapping("/hello")
    public String showForm(Model theModel) {
        
        theModel.addAttribute("emp", new Employee());
        
        return "viewpage";
    }
    
    @RequestMapping("/helloagain")
    public String processForm(
            @Valid @ModelAttribute("emp") Employee emp,
            BindingResult br) {
                
        if (br.hasErrors()) {
            return "viewpage";
        }
        else {
            return "final";
        }
    }
}

4.创建验证器注释

密码.java

package com.javatpoint.customvalidation;

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 javax.validation.Payload;

@Constraint(validatedBy = PasswordConstraintValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface Password {
    //error message
        public String message() default "must contain jtp";
    //represents group of constraints    
        public Class[] groups() default {};
    //represents additional information about annotation
        public Class[] payload() default {};
}

5.创建验证器类

PasswordConstraintValidator.java

package com.javatpoint.customvalidation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PasswordConstraintValidator implements ConstraintValidator {

    public boolean isValid(String s, ConstraintValidatorContext cvc) {
        
        boolean result=s.contains("jtp");
        return result;
    }
}

6.在web.xml文件中提供控制器的条目

web.xml



  SpringMVC
     
    spring  
    org.springframework.web.servlet.DispatcherServlet  
    1    
  
  
    spring  
    /  
  

7.在xml文件中定义bean

spring-servlet.xml



    
    
    
    
    
     
        
             
     

8.创建请求的页面

index.jsp

9.创建其他视图组件

viewpage.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


    


    
        Username:         
        

Password (*):

Age (*):

final.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>



Username: ${emp.name}

Password: ${emp.password}

Age: ${emp.age}

输出:


在这里,我们输入的密码没有“ jtp”序列。


现在,我们输入了具有“ jtp”序列的密码。