本文为作者原创,如需转载请在文首著名地址,公众号转载请申请开白。

springboot-guide : 适合新手入门以及有经验的开发人员查阅的 Spring Boot 教程(业余时间维护中,欢迎一起维护)。

数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。

本文结合自己在项目中的实际使用经验,可以说文章介绍的内容很实用,不了解的朋友可以学习一下,后面可以立马实践到项目上去。

下面我会通过实例程序演示如何在 Java 程序中尤其是 Spring 程序中优雅地的进行参数验证。

基础设施搭建

相关依赖

如果开发普通 Java 程序的的话,你需要可能需要像下面这样依赖:

   <dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.9.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>

使用 Spring Boot 程序的话只需要spring-boot-starter-web 就够了,它的子依赖包含了我们所需要的东西。除了这个依赖,下面的演示还用到了 lombok ,所以不要忘记添加上相关依赖。

    <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

实体类

下面这个是示例用到的实体类。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person { @NotNull(message = "classId 不能为空")
private String classId; @Size(max = 33)
@NotNull(message = "name 不能为空")
private String name; @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可选范围")
@NotNull(message = "sex 不能为空")
private String sex; @Email(message = "email 格式不正确")
@NotNull(message = "email 不能为空")
private String email; }

正则表达式说明:

- ^string : 匹配以 string 开头的字符串
- string$ :匹配以 string 结尾的字符串
- ^string$ :精确匹配 string 字符串
- ((^Man$|^Woman$|^UGM$)) : 值只能在 Man,Woman,UGM 这三个值中选择

下面这部分校验注解说明内容参考自:https://www.cnkirito.moe/spring-validation/ ,感谢@徐靖峰

JSR提供的校验注解:

  • @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=) 被注释的元素必须符合指定的正则表达式

Hibernate Validator提供的校验注解

  • @NotBlank(message =) 验证字符串非null,且长度必须大于0
  • @Email 被注释的元素必须是电子邮箱地址
  • @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
  • @NotEmpty 被注释的字符串的必须非空
  • @Range(min=,max=,message=) 被注释的元素必须在合适的范围内

验证Controller的输入

验证请求体(RequestBody)

Controller:

我们在需要验证的参数上加上了@Valid注解,如果验证失败,它将抛出MethodArgumentNotValidException。默认情况下,Spring会将此异常转换为HTTP Status 400(错误请求)。


@RestController
@RequestMapping("/api")
public class PersonController { @PostMapping("/person")
public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {
return ResponseEntity.ok().body(person);
}
}

ExceptionHandler:

自定义异常处理器可以帮助我们捕获异常,并进行一些简单的处理。如果对于下面的处理异常的代码不太理解的话,可以查看这篇文章 《SpringBoot 处理异常的几种常见姿势》

@ControllerAdvice(assignableTypes = {PersonController.class})
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}
}

通过测试验证:

下面我通过 MockMvc 模拟请求 Controller 的方式来验证是否生效,当然你也可以通过 Postman 这种工具来验证。

我们试一下所有参数输入正确的情况。

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PersonControllerTest {
@Autowired
private MockMvc mockMvc; @Autowired
private ObjectMapper objectMapper; @Test
public void should_get_person_correctly() throws Exception {
Person person = new Person();
person.setName("SnailClimb");
person.setSex("Man");
person.setClassId("82938390");
person.setEmail("Snailclimb@qq.com"); mockMvc.perform(post("/api/person")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(person)))
.andExpect(MockMvcResultMatchers.jsonPath("name").value("SnailClimb"))
.andExpect(MockMvcResultMatchers.jsonPath("classId").value("82938390"))
.andExpect(MockMvcResultMatchers.jsonPath("sex").value("Man"))
.andExpect(MockMvcResultMatchers.jsonPath("email").value("Snailclimb@qq.com"));
}
}

验证出现参数不合法的情况抛出异常并且可以正确被捕获。

 @Test
public void should_check_person_value() throws Exception {
Person person = new Person();
person.setSex("Man22");
person.setClassId("82938390");
person.setEmail("SnailClimb"); mockMvc.perform(post("/api/person")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(person)))
.andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围"))
.andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空"))
.andExpect(MockMvcResultMatchers.jsonPath("email").value("email 格式不正确"));
}

使用 Postman 验证结果如下:

验证请求参数(Path Variables 和 Request Parameters)

Controller:

一定一定不要忘记在类上加上 Validated 注解了,这个参数可以告诉 Spring 去校验方法参数。

@RestController
@RequestMapping("/api")
@Validated
public class PersonController { @GetMapping("/person/{id}")
public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) {
return ResponseEntity.ok().body(id);
} @PutMapping("/person")
public ResponseEntity<String> getPersonByName(@Valid @RequestParam("name") @Size(max = 6,message = "超过 name 的范围了") String name) {
return ResponseEntity.ok().body(name);
}
}

ExceptionHandler:

    @ExceptionHandler(ConstraintViolationException.class)
ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}

通过测试验证:

  @Test
public void should_check_param_value() throws Exception { mockMvc.perform(get("/api/person/6")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string("getPersonByID.id: 超过 id 的范围了"));
} @Test
public void should_check_param_value2() throws Exception { mockMvc.perform(put("/api/person")
.param("name","snailclimbsnailclimb")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string("getPersonByName.name: 超过 name 的范围了"));
}

验证 Service 中的方法

我们还可以验证任何Spring组件的输入,而不是验证控制器级别的输入,我们可以使用@Validated@Valid注释的组合来实现这一需求。

一定一定不要忘记在类上加上 Validated 注解了,这个参数可以告诉 Spring 去校验方法参数。

@Service
@Validated
public class PersonService { public void validatePerson(@Valid Person person){
// do something
}
}

通过测试验证:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PersonServiceTest {
@Autowired
private PersonService service; @Test(expected = ConstraintViolationException.class)
public void should_throw_exception_when_person_is_not_valid() {
Person person = new Person();
person.setSex("Man22");
person.setClassId("82938390");
person.setEmail("SnailClimb");
service.validatePerson(person);
} }

Validator 编程方式手动进行参数验证

某些场景下可能会需要我们手动校验并获得校验结果。

    @Test
public void check_person_manually() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Person person = new Person();
person.setSex("Man22");
person.setClassId("82938390");
person.setEmail("SnailClimb");
Set<ConstraintViolation<Person>> violations = validator.validate(person);
//output:
//email 格式不正确
//name 不能为空
//sex 值不在可选范围
for (ConstraintViolation<Person> constraintViolation : violations) {
System.out.println(constraintViolation.getMessage());
}
}

上面我们是通过 Validator 工厂类获得的 Validator 示例,当然你也可以通过 @Autowired 直接注入的方式。但是在非 Spring Component 类中使用这种方式的话,只能通过工厂类来获得 Validator

@Autowired
Validator validate

自定以 Validator(实用)

如果自带的校验注解无法满足你的需求的话,你还可以自定义实现注解。

案例一:校验特定字段的值是否在可选范围

比如我们现在多了这样一个需求:Person类多了一个 region 字段,region 字段只能是ChinaChina-TaiwanChina-HongKong这三个中的一个。

第一步你需要创建一个注解:

@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = RegionValidator.class)
@Documented
public @interface Region { String message() default "Region 值不在可选范围内"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};
}

第二步你需要实现 ConstraintValidator接口,并重写isValid 方法:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet; public class RegionValidator implements ConstraintValidator<Region, String> { @Override
public boolean isValid(String value, ConstraintValidatorContext context) {
HashSet<Object> regions = new HashSet<>();
regions.add("China");
regions.add("China-Taiwan");
regions.add("China-HongKong");
return regions.contains(value);
}
}

现在你就可以使用这个注解:

    @Region
private String region;

案例二:校验电话号码

校验我们的电话号码是否合法,这个可以通过正则表达式来做,相关的正则表达式都可以在网上搜到,你甚至可以搜索到针对特定运营商电话号码段的正则表达式。

PhoneNumber.java

import javax.validation.Constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME; @Documented
@Constraint(validatedBy = PhoneNumberValidator.class)
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
public @interface PhoneNumber {
String message() default "Invalid phone number";
Class[] groups() default {};
Class[] payload() default {};
}

PhoneNumberValidator.java

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext; public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber,String> { @Override
public boolean isValid(String phoneField, ConstraintValidatorContext context) {
if (phoneField == null) {
// can be null
return true;
}
return phoneField.matches("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$") && phoneField.length() > 8 && phoneField.length() < 14;
}
}

搞定,我们现在就可以使用这个注解了。

@PhoneNumber(message = "phoneNumber 格式不正确")
@NotNull(message = "phoneNumber 不能为空")
private String phoneNumber;

使用验证组

某些场景下我们需要使用到验证组,这样说可能不太清楚,说简单点就是对对象操作的不同方法有不同的验证规则,示例如下(这个就我目前经历的项目来说使用的比较少,因为本身这个在代码层面理解起来是比较麻烦的,然后写起来也比较麻烦)。

先创建两个接口:

public interface AddPersonGroup {
}
public interface DeletePersonGroup {
}

我们可以这样去使用验证组

@NotNull(groups = DeletePersonGroup.class)
@Null(groups = AddPersonGroup.class)
private String group;
@Service
@Validated
public class PersonService { public void validatePerson(@Valid Person person) {
// do something
} @Validated(AddPersonGroup.class)
public void validatePersonGroupForAdd(@Valid Person person) {
// do something
} @Validated(DeletePersonGroup.class)
public void validatePersonGroupForDelete(@Valid Person person) {
// do something
} }

通过测试验证:

  @Test(expected = ConstraintViolationException.class)
public void should_check_person_with_groups() {
Person person = new Person();
person.setSex("Man22");
person.setClassId("82938390");
person.setEmail("SnailClimb");
person.setGroup("group1");
service.validatePersonGroupForAdd(person);
} @Test(expected = ConstraintViolationException.class)
public void should_check_person_with_groups2() {
Person person = new Person();
person.setSex("Man22");
person.setClassId("82938390");
person.setEmail("SnailClimb");
service.validatePersonGroupForDelete(person);
}

使用验证组这种方式的时候一定要小心,这是一种反模式,还会造成代码逻辑性变差。

代码地址:https://github.com/Snailclimb/springboot-guide/tree/master/source-code/advanced/bean-validation-demo

@NotNull vs @Column(nullable = false)(重要)

在使用 JPA 操作数据的时候会经常碰到 @Column(nullable = false) 这种类型的约束,那么它和 @NotNull 有何区别呢?搞清楚这个还是很重要的!

  • @NotNull是 JSR 303 Bean验证批注,它与数据库约束本身无关。
  • @Column(nullable = false) : 是JPA声明列为非空的方法。

总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。

TODO

  • [ ] 原理分析

参考

开源项目推荐

作者的其他开源项目推荐:

  1. JavaGuide:【Java学习+面试指南】 一份涵盖大部分Java程序员所需要掌握的核心知识。
  2. springboot-guide : 适合新手入门以及有经验的开发人员查阅的 Spring Boot 教程(业余时间维护中,欢迎一起维护)。
  3. programmer-advancement : 我觉得技术人员应该有的一些好习惯!
  4. spring-security-jwt-guide :从零入门 !Spring Security With JWT(含权限验证)后端部分代码。

如何在 Spring/Spring Boot 中做参数校验?你需要了解的都在这里!的更多相关文章

  1. 如何在 Spring/Spring Boot 中做参数校验

    数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据. 本文结合自己在项目 ...

  2. 【转】spring 装配Bean中构造参数的注入

    转载自:http://www.bianceng.cn/Programming/Java/201307/37027.htm spring 装配Bean中构造参数的注入 spring装配bean中还有一种 ...

  3. Spring WebFlux 基础教程:参数校验

    请求参数校验,在实际的应用中很常见,网上的文章大部分提供的使用注解的方式做参数校验.本文主要介绍 Spring Webflux Function Endpoint 使用 Spring Validati ...

  4. 寻找写代码感觉(十六)之 集成Validation做参数校验

    写在前面 今天是大年初五了... 不知不觉,又要上班了,美好的假期只剩一天了,有点不舍呢! 也不知道为什么,总感觉像在做梦一样,像没睡醒一样,并不是因为眼睛小,更多应该是自寻烦恼,想得多罢了. 参数校 ...

  5. 使用hibernate validate做参数校验

    1.为什么使用hibernate validate ​ 在开发http接口的时候,参数校验是必须有的一个环节,当参数校验较少的时候,一般是直接按照校验条件做校验,校验不通过,返回错误信息.比如以下校验 ...

  6. spring boot 中接口参数为枚举时的反序列化配置(总结)

    步骤 如果是 GET 请求中需要反序列化枚举值(即 url 中的参数[querystring]),确保以下两点 1.1. 重写 StringToEnumConverterFactory 1.2. 配置 ...

  7. spring mvc controller中的参数验证机制(二)

    这里我们介绍以下自定义的校验器的简单的使用示例 一.包结构和主要文件 二.代码 1.自定义注解文件MyConstraint package com.knyel.validator; import ja ...

  8. Spring Validation-用注解代替代码参数校验

    Spring Validation 概念 在原先的编码中,我们如果要验证前端传递的参数,一般是在接受到传递过来的参数后,手动在代码中做 if-else 判断,这种编码方式会带来大量冗余代码,十分的不优 ...

  9. 测试开发专题:如何在spring-boot中进行参数校验

    上文我们讨论了spring-boot如何去获取前端传递过来的参数,那传递过来总不能直接使用,需要对这些参数进行校验,符合程序的要求才会进行下一步的处理,所以本篇文章我们主要讨论spring-boot中 ...

随机推荐

  1. 【Java】用Freemarker完美导出word文档(带图片)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

  2. 你所不知道的TIME_WAIT和CLOSE_WAIT

    你遇到过TIME_WAIT的问题吗? 我相信很多都遇到过这个问题.一旦有用户在喊:网络变慢了.第一件事情就是,netstat -a | grep TIME_WAIT | wc -l 一下.哎呀妈呀,几 ...

  3. logback颜色

    官网日志连接:https://logback.qos.ch/manual/layouts.html#coloring 举例 logging.pattern.console=%red(%d{yyyy-M ...

  4. Requests实践详解

    Requests是什么 Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库 如果你看过上篇文章关于urllib库的使用,你会发现, ...

  5. linux上安装LAMP笔记

    B哥最近在参加比赛,需要把一个php项目部署到服务器上,故此在linux上安装LAMP环境,用于部署项目,第一次安装,做点儿笔记记录一下. 安装条件: Redhat或者CentOS linux环境已装 ...

  6. Unreal Engine 4 系列教程 Part 1:入门

    原文:Unreal Engine 4 Tutorial for Beginners: Getting Started 作者:Tommy Tran 译者:Shuchang Liu 本篇教程将引导你安装U ...

  7. Flask中的CBV以及正则表达式

    Flask中的CBV以及正则表达式 一.CBV def auth(func): def inner(*args, **kwargs): print('before') result = func(*a ...

  8. phpstorm 新加入项目的文件--全局搜索不到 ctrl + shift + R

    通过文件名查找文件 ,能搜到其他的现有文件,只是新加入的文件,无法出现在搜索到的结果中 . 总不可能在搜索的关键词一直拼写错误吧 , 那能想到的只有缓存出问题了. 新加入的文件,新加入的文件.... ...

  9. Python开发【第十一篇】函数

    函数 什么是函数? 函数是可以重复执行的语句块,可以重复调用并执行函数的面向过程编程的最小单位. 函数的作用: 函数用于封装语句块,提高代码的重用性,定义用户级别的函数.提高代码的可读性和易维护性. ...

  10. C# 求Π Π/4=1-1/3+1/5-1/7+......+1/(2*n-3)-1/(2*n-1); (n=2000)

    double a = 0.0;//最终Π的结果 double类型 int n; for (n = 1; n <= 2000; n++) { if (n % 2 == 1) { a += 1.0 ...