📜  Spring MVC编号验证

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

Spring MVC编号验证

在Spring MVC Validation中,我们可以在一个数字范围内验证用户的输入。以下注释用于实现数字验证:

  • @Min批注-需要传递带有@Min批注的整数值。用户输入必须等于或大于此值。
  • @Max批注-需要传递带有@Max批注的整数值。用户输入必须等于或小于此值。

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

public class Employee {

    private String name;
    @Size(min=1,message="required")
    private String pass;
    
    @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 getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    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 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

<%@ 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:

Age:

final.jsp



Username: ${param.name} 
Password: ${param.pass}
Age: ${param.age }

输出: