一.使用Spring的Validation校验
1.导入使用Spring需要导入的jar包
2.配置web.xml文件:配置前端控制器:
3.编写视图:<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringMVCValidation</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 让servlet随服务启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app>
loginForm.jsp:
success.jsp:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试Validator接口验证</title> </head> <body> <h3>登录界面</h3> <form:form modelAttribute="user" method="post" action="login.action"> <table> <tr> <td>登录名:</td> <td><form:input path="loginname"/></td> <!-- 显示loginname属性的错误信息 --> <td><form:errors path="loginname" cssStyle="color:red"/></td> </tr> <tr> <td>密码:</td> <td><form:input path="password"/></td> <!-- 显示password属性的错误信息 --> <td><form:errors path="password" cssStyle="color:red"/></td> </tr> <tr> <td><input type="submit" value="登录"/></td> </tr> </table> </form:form> </body> </html>
4.编写实体类(持久化类):User.java<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> 登录成功 </body> </html>
5.编写验证器:UserValidator.javapackage com.domain; import java.io.Serializable; public class User implements Serializable{ private String loginname; private String password; public User() { // TODO Auto-generated constructor stub } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
6.编写处理器handler:UserController.javapackage com.validator; import org.springframework.stereotype.Repository; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.domain.User; /** * 实现Spring的Validator接口的用户验证器 * @author ${HLoach} * 2017年4月6日 */ @Repository("userValidator")//该注解将该对象注释为Spring容器中的一个Bean,名字为"userValidator" public class UserValidator implements Validator{ //该验证器能够对clazz类型的对象进行校验 @Override public boolean supports(Class<?> clazz) { //User指定的Class参数所表示的类或接口是否相同,或是否是其超类或超接口 return User.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { /** * 使用ValidationUtils中的一个静态方法rejectIfEmpty()来对loginname属性进行校验, * 如果loginname属性是null或者空字符串的话,就拒绝验证通过。 */ ValidationUtils.rejectIfEmpty(errors, "loginname", null, "登录名不能为空"); ValidationUtils.rejectIfEmpty(errors, "password", null, "密码不能为空"); User user = (User) target; if(user.getLoginname() != null && !user.getLoginname().equals("") && user.getLoginname().length() > 10){ //使用Errors的rejectValue方法验证 errors.rejectValue("loginname", null, "用户名不能超过10个字符"); } if(user.getPassword() != null && !user.getPassword().equals("") && user.getPassword().length() < 6){ errors.rejectValue("password", null, "密码不能小于6位"); } } }
package com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.domain.User; import com.validator.UserValidator; /** * 处理请求的handler * @author ${HLoach} * 2017年4月6日 */ @Controller public class UserController { @Autowired//自动装配 @Qualifier("userValidator") private UserValidator userValidator; @RequestMapping(value="/login",method=RequestMethod.POST) public String login( @ModelAttribute User user, Model model, Errors errors ){ model.addAttribute("user", user); //调用userValidator的验证方法 userValidator.validate(user, errors); //如果验证不通过,那么跳转回登录界面 if(errors.hasErrors()){ return "loginForm"; } return "success"; } @RequestMapping("/{formName}") public String show(@PathVariable String formName,Model model){ User user = new User(); model.addAttribute("user", user); return formName; } }
7.配置SpringMVC的配置文件:springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 扫描加载固定包下面的注解类 --> <context:component-scan base-package="com.controller,com.validator"/> <!-- 加载适配器和映射器等 --> <mvc:annotation-driven/> <!-- 加载静态文件 --> <!-- <mvc:default-servlet-handler/> --> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 <property name="prefix"> <value>/WEB-INF/</value> </property>--> <!-- 后缀 --> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
二.JSR 303校验
JSR 303目前有两个实现,第一个实现是Hibernate Validator,可以从以下网站上下载:
https://sourceforge.net/projects/hibernate/files/hibernate-validator/
第二个是Apache bval,可以从以下网站下载:
Apache bval实现JSR 303和Hibernate Validator实现JSR 303基本一样,主要在于需要导入各自的包
例如:Apache bval实现JSR 303
1.在导入Spring的jar包的基础上,还需要导入Apache bval的jar包:
2.web.xml同第一点,SpringMVC的配置文件springmvc.xml如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 扫描加载固定包下面的注解类 --> <context:component-scan base-package="com.controller"/> <!-- 加载适配器和映射器等 --> <mvc:annotation-driven/> <!-- 加载静态文件 --> <!-- <mvc:default-servlet-handler/> --> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 <property name="prefix"> <value>/WEB-INF/</value> </property>--> <!-- 后缀 --> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
3.编写实体类(持久化类):Users.java
package com.domain; import java.io.Serializable; import java.util.Date; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import javax.validation.constraints.Pattern; import org.apache.bval.constraints.Email; import org.apache.bval.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; public class Users implements Serializable{ @NotEmpty(message="登录名不能为空") private String loginname; @NotEmpty(message="密码不能为空") private String password; @NotNull(message="年龄不能为空") @Min(value=18,message="年龄必须大于或者等于18岁")//Hibernate Validation可以使用@Range(min,max,message)验证属性值必须在合适的范围内 private Integer age; @Email(message="必须是合法的邮箱地址") private String email; @DateTimeFormat(pattern="yyyy-MM-dd")//设定日期格式 @Past(message="生日必须是一个过去的日期") private Date birthDay; @Pattern(regexp="[1][3,8][2,3,6,9][0-9]{8}",message="无效的电话号码") private String phone; public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
4.编写视图:
registerForm.jsp:
success.jsp:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试JSR 303</title> </head> <body> <form:form modelAttribute="users" method="post" action="register.action"> <table> <tr> <td>登录名:</td> <td><form:input path="loginname"/></td> <td><form:errors path="loginname" cssStyle="color:red"/></td> </tr> <tr> <td>密码:</td> <td><form:input path="password"/></td> <td><form:errors path="password" cssStyle="color:red"/></td> </tr> <tr> <td>年龄:</td> <td><form:input path="age"/></td> <td><form:errors path="age" cssStyle="color:red"/></td> </tr> <tr> <td>邮箱:</td> <td><form:input path="email"/></td> <td><form:errors path="email" cssStyle="color:red"/></td> </tr> <tr> <td>生日(格式:2000-1-1):</td> <td><form:input path="birthDay"/></td> <td><form:errors path="birthDay" cssStyle="color:red"/></td> </tr> <tr> <td>电话:</td> <td><form:input path="phone"/></td> <td><form:errors path="phone" cssStyle="color:red"/></td> </tr> <tr> <td><input type="submit" value="注册"/></td> </tr> </table> </form:form> </body> </html>
5.编写处理器handler:UsersController.java<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试JSR 303</title> </head> <h3>测试JSR 303</h3> 登录名:${requestScopr.users.loginname } 密码:${requestScopr.users.password } 年龄:${requestScopr.users.age } 邮箱:${requestScopr.users.email } 生日:${requestScopr.users.birthDay } 电话:${requestScopr.users.phone } </body> </html>
package com.controller; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.domain.Users; /** * * @author ${HLoach} * 2017年4月7日 */ @Controller public class UsersController { @RequestMapping("/{formName}") public String show(@PathVariable String formName,Model model){ Users users = new Users(); model.addAttribute("users", users); return formName; } @RequestMapping(value="/register",method=RequestMethod.POST) public String register( @Valid @ModelAttribute Users users, Errors errors, Model model ){ //如果验证不通过,那么跳转回登录界面 if(errors.hasErrors()){ return "registerForm"; } model.addAttribute("users", users); return "success"; } }
注意:Errors errors必须紧跟在@Valid @ModelAttribute Users users之后,否则会出现400错误。测试结果如下: