📅  最后修改于: 2020-12-04 08:45:25             🧑  作者: Mango
在Spring MVC Validation中,我们可以在一个数字范围内验证用户的输入。以下注释用于实现数字验证:
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
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;
}
}
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";
}
}
}
web.xml
SpringMVC
spring
org.springframework.web.servlet.DispatcherServlet
1
spring
/
spring-servlet.xml
index.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
Click here...
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 }
输出: