📅  最后修改于: 2020-12-04 08:44:16             🧑  作者: Mango
Spring MVC Validation允许我们以特定顺序(即正则表达式)验证用户输入。 @Pattern批注用于实现正则表达式验证。在这里,我们可以为regexp属性提供所需的正则表达式,并将其与注释一起传递。
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.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;
}
}
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
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(*):
final.jsp
Username: ${emp.name}
Password: ${emp.pass}
输出: