数据校验概述
数据校验
就是用来验证用户输入的数据是否合法,比如用户登录时,用户名不能为空,或者不能超出指定长度等要求。
数据校验分为客户端校验
和服务端校验
。客户端校验一般通过js校验。但客户端校验往往容易有人绕过页面,就会出现非法数据,所以服务端也要数据校验。
服务端校验通常使用hibernate
的校验框架。
数据校验过程
第一步:创建SpringMVC工程
参考 【SpringMVC】SpringMVC入门实例创建一个SpringMVC工程
创建好的工程目录如下:
在pom.xml
中添加hibernate-validator
和taglibs
依赖
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.5</version>
</dependency>
完整的pom.xml
文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lucas</groupId>
<artifactId>SpringValidate</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringValidate Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!--spring 版本号-->
<spring.version>5.2.7.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring 核心包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring end -->
<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-alpha0</version>
<scope>test</scope>
</dependency>
<!--j2ee相关包 servlet、jsp、jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
<build>
<finalName>SpringValidate</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
第二步:注册校验器
在dispatcher-servlet.xml
中注册 hibernate 的校验器,并在原来的 mvc 注解驱动中设置 validator 属性:
<!--开启mvc注解驱动 -->
<mvc:annotation-driven validator="validator" />
<!-- 注册hibernate的校验器 -->
<bean id = "validator" class = "org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value ="org.hibernate.validator.HibernateValidator"></property>
</bean>
新建实体类,在实体类上加相应的校验注解
public class User {
private int id;
@Min(value = 18,message = "年龄不能小于18岁")
private int age;
@NotEmpty(message="姓名不能为空")
@Length(min = 6,message = "姓名长度不能小于6位")
private String name;
@NotEmpty(message="邮箱不能为空")
@Email(message="邮箱格式不正确")
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
常用注解如下
注解 | 说明 |
---|---|
@Null | 被注解的元素必须为 null |
@NotNull | 被注解的元素必须不为 null |
@AssertTrue | 被注解的元素必须为 true |
@AssertFalse | 被注解的元素必须为 false |
@Min(value) | 被注解的元素必须是一个数字,其值必须大于等于指定的最小值 |
@Max(value) | 被注解的元素必须是一个数字,其值必须小于等于指定的最大值 |
@DecimalMin(value) | 被注解的元素必须是一个数字,其值必须大于等于指定的最小值 |
@DecimalMax(value) | 被注解的元素必须是一个数字,其值必须小于等于指定的最大值 |
@Size(max=, min=) | 被注解的元素的大小必须在指定的范围内 |
@Digits (integer, fraction) | 被注解的元素必须是一个数字,其值必须在可接受的范围内 |
@Past | 被注解的元素必须是一个过去的日期 |
@Future | 被注解的元素必须是一个将来的日期 |
@Pattern(regex=,flag=) | 被注解的元素必须符合指定的正则表达式 |
被注解的元素必须是电子邮箱地址 | |
@NotBlank(message =) | 验证字符串非null,且长度必须大于0 |
@Length(min=,max=) | 被注解的字符串的大小必须在指定的范围内 |
@NotEmpty | 被注解的字符串的必须非空 |
@Range(min=,max=,message=) | 被注解的元素必须在合适的范围内 |
第三步:Controller中添加校验
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/login")
public String login(){
return "login";
}
/**
* @Validated user 表示user接收的数据需要根据指定的规则进行校验
* BindingResult 封装验证结果,必须紧跟在验证变量之后,
* 如果有多个信息需要验证那么就有多个BindingResult参数
*
*/
@RequestMapping("/add")
public String add(@Validated User user, BindingResult br, Model m){
System.out.println(user);
// 获取验证信息
List<ObjectError> allErrors = br.getAllErrors();
for (ObjectError objectError : allErrors) {
System.out.println(objectError.getDefaultMessage());
}
// 将验证信息保存到作用域中
m.addAttribute("errors", allErrors);
return "result";
}
}
第四步:测试运行
修改login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/add" method="post">
<div>
名字:<input name="name" >
</div>
<div>
年龄:<input name="age" >
</div>
<div>
邮箱:<input name="email" >
</div>
<div>
<input type="submit" value="添加用户">
</div>
</form>
</body>
</html>
添加result.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
tet
<c:if test="${errors ne null }">
<c:forEach items="${errors}" var="e">
${e.defaultMessage}<br>
</c:forEach>
</c:if>
</body>
</html>
运行结果如下:
最后再来看一下工程目录结构