一起来学SpringBoot(十七)优雅的参数校验

参数校验

在开发中经常需要写一些字段校验的代码,比如字段非空,字段长度限制,邮箱格式验证等等,写这些与业务逻辑关系不大的代码个人感觉有两个麻烦:

  • 验证代码繁琐,重复劳动
  • 方法内代码显得冗长
  • 每次要看哪些参数验证是否完整,需要去翻阅验证逻辑代码

你看这样?我感觉不行 ~有啥好办法不

public String test1(String name) {
   
    if (name == null) {
   
        throw new NullPointerException("name 不能为空");
    }
    if (name.length() < 2 || name.length() > 10) {
   
        throw new RuntimeException("name 长度必须在 2 - 10 之间");
    }
    return "success";
}

使用hibernate-validator

spring-boot-starter-web包里面有hibernate-validator包,不需要引用hibernate validator依赖。在 pom.xml 中添加上 spring-boot-starter-web 的依赖即可

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

创建如下实体

@Data
public class Book {
   
    private Integer id;
    @NotBlank(message = "name 不允许为空")
    @Length(min = 2, max = 10, message = "name 长度必须在 {min} - {max} 之间")
    private String name;
}

实体校验

然后呢在 controller 中这样写即可验证

验证加@RequestBody 的参数

@RequestMapping("/test")
public String test(@Validated @RequestBody  Book book) {
   
	return "success";
}

这时候呢会出现MethodArgumentNotValidException异常可以在ControllerAdvice 做全局异常处理

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public ResponseEntity<ModelMap> ex(Exception e) {
   
    log.error("请求参数不合法。", e);
    ModelMap modelMap = new ModelMap();
    if (e instanceof MethodArgumentNotValidException) {
   
        modelMap.put("message", getErrors(((MethodArgumentNotValidException) e).getBindingResult()));
    } 
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(modelMap);
}

private Map<String, String> getErrors(BindingResult result) {
   
    Map<String, String> map = new HashMap<>();
    List<FieldError> list = result.getFieldErrors();
    for (FieldError error : list) {
   
        map.put(error.getField(), error.getDefaultMessage());
    }
    return map;
}

如果不加呢?

@RequestMapping("/test")
public String test(@Validated Book book) {
   
	return "success";
}

则会出BindException 异常,则又可以在ControllerAdvice 中加入判断

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public ResponseEntity<ModelMap> ex(Exception e) {
   
    log.error("请求参数不合法。", e);
    ModelMap modelMap = 
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值