Spring Boot 实现接口的各种参数校验

Spring Validation是对hibernate validation的二次封装,用于支持spring mvc参数自动校验。接下来,我们以spring-boot项目为例,介绍Spring Validation的使用。

1.添加依赖

===================================================================

org.hibernate.validator

hibernate-validator

org.projectlombok

lombok

2.接口参数校验

=====================================================================

对于web服务来说,为防止非法参数对业务造成影响,在Controller层一定要做参数校验的!大部分情况下,请求参数分为如下两种形式:

  • POST、PUT请求,使用requestBody传递参数;

  • GET请求,使用requestParam/PathVariable传递参数。

下面我们简单介绍下requestBody和requestParam/PathVariable的参数校验实战!

2.1 requestBody参数校验


POSTPUT请求一般会使用requestBody传递参数,这种情况下,后端使用DTO对象进行接收。只要给 DTO 对象加上@Validated注解就能实现自动参数校验。

比如,有一个保存User的接口,要求userName长度是2-10,account和password字段长度是6-20。如果校验失败,会抛出MethodArgumentNotValidException异常,Spring默认会将其转为400(Bad Request)请求。

DTO 表示数据传输对象(Data Transfer Object),用于服务器和客户端之间交互传输使用的。在 spring-web 项目中可以表示用于接收请求参数的Bean对象。

我们只需要两步就可以实现刚刚对user对象参数的需求

  • 1.在实体类上声明约束注解

import lombok.Data;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;

@Data

public class UserDTO {

private Long userId;

@NotNull

@Length(min = 2, max = 10)

private String userName;

@NotNull

@Length(min = 6, max = 20)

private String account;

@NotNull

@Length(min = 6, max = 20)

private String password;

}

  • 2.在接口方法参数上声明校验注解

import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

import java.util.Map;

@RestController

public class UserController {

@PostMapping(“/save”)

public Map<String, Object> saveUser(@RequestBody @Validated UserDTO userDTO) {

Map<String, Object> result = new HashMap<>();

result.put(“code”, 20000);

return result;

}

}

接下来我们进行一下测试

在这里插入图片描述

我们可以看到密码位数不对时会转为400请求参数不对的错误

2.2 requestParam/PathVariable参数校验


GET请求一般会使用requestParam/PathVariable传参。

如果参数比较多 (比如超过 6 个),还是推荐使用DTO对象接收。否则,推荐将一个个参数平铺到方法入参中。在这种情况下,必须在Controller类上标注@Validated注解,并在入参上声明约束注解 (如@Min等)。

如果校验失败,会抛出ConstraintViolationException异常。代码示例如下:

package com.example.code.controller;

import com.example.code.po.UserDTO;

import org.hibernate.validator.constraints.Length;

import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

import java.util.HashMap;

import java.util.Map;

@RestController

public class UserController {

@GetMapping(“{userId}”)

public Map<String, Object> detail(@PathVariable(“userId”) @Min(10000000000000000L) Long userId) {

Map<String, Object> result = new HashMap<>();

UserDTO userDTO = new UserDTO();

userDTO.setUserId(userId);

userDTO.setAccount(“11111111111111111”);

userDTO.setUserName(“xixi”);

userDTO.setAccount(“11111111111111111”);

result.put(“code”, 20000);

result.put(“data”, userDTO);

return result;

}

@GetMapping(“getByAccount”)

public Map<String, Object> getByAccount(@Length(min = 6, max = 20) @NotNull String account) {

Map<String, Object> result = new HashMap<>();

UserDTO userDTO = new UserDTO();

userDTO.setUserId(10000000000000003L);

userDTO.setAccount(account);

userDTO.setUserName(“xixi”);

userDTO.setAccount(account);

result.put(“code”, 20000);

result.put(“data”, userDTO);

return result;

}

}

在这里插入图片描述

3.统一异常处理

=====================================================================

在我们刚刚的测试中会发现如果校验失败,会抛出MethodArgumentNotValidException或者ConstraintViolationException异常。

但是在实际项目开发中,通常会用统一异常处理来返回一个更友好的提示。比如我们系统要求无论发送什么异常,http的状态码必须返回200,由业务码去区分系统的异常情况。

import org.springframework.http.HttpStatus;

import org.springframework.validation.BindingResult;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.ResponseStatus;

import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

import java.util.HashMap;

import java.util.Map;

@RestControllerAdvice

public class CommonExceptionHandler {

@ExceptionHandler({MethodArgumentNotValidException.class})

@ResponseStatus(HttpStatus.OK)

@ResponseBody

public Map<String, Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {

Map<String, Object> result = new HashMap<>();

BindingResult bindingResult = ex.getBindingResult();

StringBuilder sb = new StringBuilder(“校验失败:”);

for (FieldError fieldError : bindingResult.getFieldErrors()) {

sb.append(fieldError.getField()).append(“:”).append(fieldError.getDefaultMessage()).append(", ");

}

String msg = sb.toString();

result.put(“code”, 500);

result.put(“msg”, msg);

return result;

}

@ExceptionHandler({ConstraintViolationException.class})

@ResponseStatus(HttpStatus.OK)

@ResponseBody

public Map<String, Object> handleConstraintViolationException(ConstraintViolationException ex) {

Map<String, Object> result = new HashMap<>();

result.put(“code”, 500);

result.put(“msg”, ex.getMessage());

return result;

}

}

在这里插入图片描述

4.进阶使用

===================================================================

4.1 分组校验


在实际项目中,可能多个方法需要使用同一个DTO类来接收参数,而不同方法的校验规则很可能是不一样的。

这个时候,简单地在DTO类的字段上加约束注解无法解决这个问题。因此,spring-validation支持了分组校验的功能,专门用来解决这类问题。

还是继续使用上面的例子,比如保存User的时候,UserId是可空的,但是更新User的时候,UserId的值必须>=10000000000000000L;其它字段的校验规则在两种情况下一样。这个时候使用分组校验的代码示例如下:

import lombok.Data;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

@Data

public class UserDTO_Groups {

@Min(value = 10000000000000000L, groups = Update.class)

private Long userId;

@NotNull(groups = {Save.class, Update.class})

@Length(min = 2, max = 10, groups = {Save.class, Update.class})

private String userName;

@NotNull(groups = {Save.class, Update.class})

@Length(min = 6, max = 20, groups = {Save.class, Update.class})

private String account;

@NotNull(groups = {Save.class, Update.class})

@Length(min = 6, max = 20, groups = {Save.class, Update.class})

private String password;

public interface Save {

}

public interface Update {

}

}

在@Validated注解上指定校验分组

import com.example.code.po.UserDTO;

import com.example.code.po.UserDTO_Groups;

import org.hibernate.validator.constraints.Length;

import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

import java.util.HashMap;

import java.util.Map;

@RestController

public class UserController {

@PostMapping(“/save_group”)

public Map<String, Object> saveUser_Group(@RequestBody @Validated(UserDTO_Groups.Save.class) UserDTO_Groups userDTO) {

Map<String, Object> result = new HashMap<>();

result.put(“code”, 20000);

result.put(“data”, userDTO);

return result;

}

@PostMapping(“/update_group”)

public Map<String, Object> updateUser(@RequestBody @Validated(UserDTO_Groups.Update.class) UserDTO_Groups userDTO) {

Map<String, Object> result = new HashMap<>();

result.put(“code”, 20000);

result.put(“data”, userDTO);

return result;

}

}

4.2 嵌套校验


在实际开发中,我们保存User信息的时候同时还带有Job信息。需要注意的是,此时DTO类的对应字段必须标记@Valid注解。

import lombok.Data;

import org.hibernate.validator.constraints.Length;

import javax.validation.Valid;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

/**

  • 嵌套校验

*/

@Data

public class UserDTO_Nest {

@Min(value = 10000000000000000L, groups = Update.class)

private Long userId;

@NotNull(groups = {Save.class, Update.class})

@Length(min = 2, max = 10, groups = {Save.class, Update.class})

private String userName;

@NotNull(groups = {Save.class, Update.class})

@Length(min = 6, max = 20, groups = {Save.class, Update.class})

private String account;

@NotNull(groups = {Save.class, Update.class})

@Length(min = 6, max = 20, groups = {Save.class, Update.class})

private String password;

@NotNull(groups = {Save.class, Update.class})

@Valid

private Job job;

public interface Save {

}

public interface Update {

}

}

import lombok.Data;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

@Data

public class Job {

@Min(value = 1, groups = UserDTO_Nest.Update.class)

private Long jobId;

@NotNull(groups = {UserDTO_Nest.Save.class, UserDTO_Nest.Update.class})

@Length(min = 2, max = 10, groups = {UserDTO_Nest.Save.class, UserDTO_Nest.Update.class})

private String jobName;

@NotNull(groups = {UserDTO_Nest.Save.class, UserDTO_Nest.Update.class})

@Length(min = 2, max = 10, groups = {UserDTO_Nest.Save.class, UserDTO_Nest.Update.class})

private String position;

}

package com.example.code.controller;

import com.example.code.po.UserDTO;

import com.example.code.po.UserDTO_Groups;

import com.example.code.po.UserDTO_Nest;

import com.example.code.validate.ValidationList;

import org.hibernate.validator.constraints.Length;

import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

import java.util.HashMap;

import java.util.Map;

@RestController

public class UserController {

@PostMapping(“/save1”)

public Map<String, Object> save1(@RequestBody @Validated(UserDTO_Nest.Save.class) UserDTO_Nest userList) {

Map<String, Object> result = new HashMap<>();

result.put(“code”, 20000);

result.put(“data”, userList);

return result;

}

}

因为我们在代码中设置了嵌套校验要求job不能为空,所以:

在这里插入图片描述

我们在job类汇总设置了position最小长度为2,所以:

在这里插入图片描述

嵌套校验可以结合分组校验一起使用。

嵌套集合校验会对集合里面的每一项都进行校验,例如List< Job>字段会对这个list里面的每一个Job对象都进行校验。

4.3 集合校验


如果请求体直接传递了json数组给后台,并希望对数组中的每一项都进行参数校验。

此时,如果我们直接使用java.util.Collection下的list或者set来接收数据,参数校验并不会生效!我们可以使用自定义list集合来接收参数:

  • 1.包装List类型,并声明@Valid注解

package com.example.code.validate;

import lombok.experimental.Delegate;

import javax.validation.Valid;

import java.util.ArrayList;

import java.util.List;

public class ValidationList implements List {

@Delegate

@Valid

public List list = new ArrayList<>();

@Override

public String toString() {

return list.toString();

}

}

注意:@Delegate注解受lombok版本限制,1.18.6以上版本可支持。如果校验不通过,会抛出NotReadablePropertyException,同样可以使用统一异常进行处理。

接下来我们开发接口,使其可以批量保存

import com.example.code.po.UserDTO;

import com.example.code.po.UserDTO_Groups;

import com.example.code.po.UserDTO_Nest;

import com.example.code.validate.ValidationList;

import org.hibernate.validator.constraints.Length;

import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

import java.util.HashMap;

import java.util.Map;

@RestController

public class UserController {

@PostMapping(“/saveList”)

public Map<String, Object> saveList(@RequestBody @Validated(UserDTO_Nest.Save.class) ValidationList<UserDTO_Nest> userList) {

Map<String, Object> result = new HashMap<>();

result.put(“code”, 20000);

result.put(“data”, userList);

return result;

}

}

总结

互联网大厂比较喜欢的人才特点:对技术有热情,强硬的技术基础实力;主动,善于团队协作,善于总结思考。无论是哪家公司,都很重视高并发高可用技术,重视基础,所以千万别小看任何知识。面试是一个双向选择的过程,不要抱着畏惧的心态去面试,不利于自己的发挥。同时看中的应该不止薪资,还要看你是不是真的喜欢这家公司,是不是能真的得到锻炼。其实我写了这么多,只是我自己的总结,并不一定适用于所有人,相信经过一些面试,大家都会有这些感触。

**另外本人还整理收藏了2021年多家公司面试知识点以及各种技术点整理 **

下面有部分截图希望能对大家有所帮助。

在这里插入图片描述
on.Validated;

import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

import java.util.HashMap;

import java.util.Map;

@RestController

public class UserController {

@PostMapping(“/saveList”)

public Map<String, Object> saveList(@RequestBody @Validated(UserDTO_Nest.Save.class) ValidationList<UserDTO_Nest> userList) {

Map<String, Object> result = new HashMap<>();

result.put(“code”, 20000);

result.put(“data”, userList);

return result;

}

}

总结

互联网大厂比较喜欢的人才特点:对技术有热情,强硬的技术基础实力;主动,善于团队协作,善于总结思考。无论是哪家公司,都很重视高并发高可用技术,重视基础,所以千万别小看任何知识。面试是一个双向选择的过程,不要抱着畏惧的心态去面试,不利于自己的发挥。同时看中的应该不止薪资,还要看你是不是真的喜欢这家公司,是不是能真的得到锻炼。其实我写了这么多,只是我自己的总结,并不一定适用于所有人,相信经过一些面试,大家都会有这些感触。

**另外本人还整理收藏了2021年多家公司面试知识点以及各种技术点整理 **

下面有部分截图希望能对大家有所帮助。

[外链图片转存中…(img-v5vf2ObG-1718716840199)]

  • 25
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值