11.5. Validation
36. Validation
从springboot-2.3开始,校验包被独立成了一个starter组件,所以需要引入validation和web,而springboot-2.3之前的版本只需要引入 web 依赖就可以了
1、常用注解
@NotNull:使用在Bean的字段注解中。它是 JSR303(Bean的校验框架)的注解,在controller的方法中验证时(运行时检查一个属性是否为空)使用,如果不合法(为空),注解中的提示信息会保存在result中。
@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(value):被注释的元素必须符合指定的正则表达式。
@Email:被注释的元素必须是电子邮件地址
@Length:被注释的字符串的大小必须在指定的范围内
@Range:被注释的元素必须在合适的范围内
@NotEmpty:用在集合类上,不能为null,并且长度必须大于0
@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0
2、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 依赖包 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
3、Spring Boot-Dependency 'org.springframework.boot:spring-boot-starter-xxx:xxx' not found-解决办法
4、实体类
package com.example.demo.model;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
@Data
public class UserRequest {
@NotNull(message = "用户名不能为空")
@Max(value = 16, message = "用户名长度不能大于16")
private String userName;
@DecimalMin(value = "18",message = "年龄不能小于18岁")
@DecimalMax(value = "25",message = "年龄不能大于25岁")
@NotNull(message = "年龄不能为空")
private Integer age;//年龄
@NotEmpty(message = "邮件不能为空")
@Email(message = "邮件格式不正确")
private String email;//邮件
@Length(min = 6,max = 18,message = "密码长度必须位于6到18之间")
private String password;
@NotEmpty(message = "请填写手机号")
private String mobile;
}
5、Controller
package com.example.demo.controller;
import com.example.demo.model.UserRequest;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
@Validated
@RestController
public class TestController {
@RequestMapping("test1")
public String getTest1(@NotBlank(message = "参数不能为空") String name, HttpServletRequest request) {
System.out.println("{token="+request.getHeader("token") +",name="+request.getParameter("name")+"}");
return "111111";
}
@RequestMapping("test2")
public String getTest2(@Valid UserRequest request, BindingResult bindingResult) {
boolean hasErrors = bindingResult.hasErrors();
List<ObjectError> allErrors = bindingResult.getAllErrors();
return "a=> {"+request.toString() +"};b=> {"+ request.getUserName() + "," +request.getPassword()+"}";
}
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String Get() {
return "get";
}
@RequestMapping(value = "/index",method = RequestMethod.POST)
public String Create() {
return "create";
}
@RequestMapping(value = "/index",method = RequestMethod.PUT)
public String Update() {
return "update";
}
@RequestMapping(value = "/index",method = RequestMethod.DELETE)
public String Delete() {
return "delete";
}
}
6、跨域配置文件 CorsConfig.java
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").
allowedOrigins("https://www.***.com"). //允许跨域的域名,可以用*表示允许任何域名使用
allowedMethods("GET", "POST", "DELETE", "PUT").
//allowedMethods("*"). //允许任何方法(post、get等)
allowCredentials(true). //带上cookie信息
allowedHeaders("*"). //允许任何请求头
maxAge(3600).
exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
}
*
*
*