spring - validation
validation就是前段传来的数据和数据的约束条件进行对比,对数据添加条件的
配置文件 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.wm</groupId>
<artifactId>validation_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>validation_demo 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>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<!--provided在debug的时候存在在release的时候就自动去掉了-->
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<!-- 主要是这个依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
</dependencies>
<build>
<finalName>validation_demo</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.0.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.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</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>
web.xml的配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--加载前段处理器-->
<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:spring-web.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
sping-web.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:mvc="http://www.springframework.org/schema/context"
xmlns:context="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:component-scan base-package="com.wm.controller"/>
<context:annotation-driven validator="myvalidator"/>
<!--声明了校验器 这里的id不能缺少-->
<bean id="myvalidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean>
</beans>
使用的方法
validation 是用注解的方式写在实体类的元素上加上注解进行约束的.
这里以Phone的实体类进行演示
package com.wm.entity;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.Date;
/**
* 〈手痒〉<br>
* 〈〉
*
* @author 11493
* @create 2018/6/8
* @since 1.0.0
*/
public class Phone {
// 校验字符串是否空白的
// @NotNull 校验不为空
@NotBlank(message = "品牌不能为空")
private String brand;
// 正则表达式 []代表的是 一位
// {3} 有3个和前面一样的
// ? 前面这个元素可以出现一次或者没有
// * 0-n个元素
// + 1-n个元素
// ()可以阔到一起,统一匹配规则
@Pattern(regexp = "[A-Z]([A-Za-z0-9]{3}){1,3}-[0-9]{3,4}[A-Z]?")
private String model;
// 最小值为0
@NotNull(message = "价钱不能为空")
@Min(value = 0,message = "不能比零小")
private Double price;
private Date launchDate;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getLaunchDate() {
return launchDate;
}
public void setLaunchDate(Date launchDate) {
this.launchDate = launchDate;
}
}
注解的含义
@Null | 被注释的元素必须为 null |
---|---|
@NotNull | 被注释的元素必须不为 null |
@NotEmpty | 被注释的字符串的必须非空 |
@NotBlank | 验证字符串非null,且长度必须大于0 |
@Min(value) | 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@Max(value) | 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@Size(max=, min=) | 被注释的元素的大小必须在指定的范围内 |
@Pattern(regex=) | 被注释的元素必须符合指定的正则表达式 |
被注释的元素必须是电子邮箱地址 | |
@DecimalMin(value) | 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@DecimalMax(value) | 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@Digits(integer, fraction) | 被注释的元素必须是一个数字,其值必须在可接受的范围内 |
@Past | 被注释的元素必须是一个过去的日期 |
@Future | 被注释的元素必须是一个将来的日期 |
@Length(min=,max=) | 被注释的字符串的大小必须在指定的范围内 |
@Range(min=,max=) | 被注释的元素必须在合适的范围内 |
@AssertTrue | 被注释的元素必须为 true |
@AssertFalse | 被注释的元素必须为 false |
controller层中验证测试
package com.wm.controller;
import com.wm.entity.Phone;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
/**
* 〈手痒〉<br>
* 〈〉
*
* @author 11493
* @create 2018/6/8
* @since 1.0.0
*/
// mvc框架中的controller注入器
@Controller
@RequestMapping("/phone")
public class PhoneController {
@RequestMapping("/add")
public void add(@Valid/*校验*/ Phone phone,/*必须加一个bindingResult 是个返回结果*/BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// 判断结果是否有错误 field 是字段的意思
// FieldError brand = bindingResult.getFieldError("brand");
// System.out.println(brand.getDefaultMessage());
System.out.println("没有通过校验");
}else {
System.out.println("通过了校验");
}
}
}