📜  Spring MVC正则表达式验证

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

Spring MVC正则表达式验证

Spring MVC Validation允许我们以特定顺序(即正则表达式)验证用户输入。 @Pattern批注用于实现正则表达式验证。在这里,我们可以为regexp属性提供所需的正则表达式,并将其与注释一起传递。

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.Pattern;
public class Employee {

    private String name;
    @Pattern(regexp="^[a-zA-Z0-9]{3}",message="length must be 3")
    private String pass;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
}

3.创建控制器类

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 display(Model m)
    {
        m.addAttribute("emp", new Employee());
        return "viewpage";
    }
    @RequestMapping("/helloagain")
    public String submitForm(@Valid @ModelAttribute("emp") Employee e, BindingResult br)
    {
        if(br.hasErrors())
        {
            return "viewpage";
        }
        else
        {
        return "final";
        }
    }
}

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

web.xml



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

5.在xml文件中定义bean

spring-servlet.xml



    
    
    
    
    
     
        
             
     

6.创建请求的页面

index.jsp

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


Click here...


7.创建其他视图组件

viewpage.jsp

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






Username:  

Password(*):

final.jsp



Username: ${emp.name} 

Password: ${emp.pass}

输出: