VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • springboot 参数校验

1、场景

1)参数为实体类

web层需要对前端传输的数据做校验,如果按照下面的代码写,就太浪费时间了,并且代码看起来很乱。

public AjaxResult queryUserProjectContent(AppletProject appletProject){
  if (appletProject.getId() == null) {
    return AjaxResult.error("id为空");
  }
  if (appletProject.getContent() == null) {
    return AjaxResult.error("内容为空");
  }
  if (appletProject.getTitle() == null) {
    return AjaxResult.error("标题为空");
  }
  if (appletProject.getCoverImg() == null) {
    return AjaxResult.error("首图为空");
  }
}
2)参数为单类型数据
public AjaxResult queryDownloadInfo(String outTradeNo){
  if(outTradeNo == null) {
    return AjaxResult.error("错误");
  }
  Map<String, Object> map = microProjectService.queryDownloadInfo(outTradeNo);
  return AjaxResult.success(map);
}

2、改进

1)入参为实体类

引入pom

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.3.1.Final</version>
</dependency>

实体类加上注解

@Data
public class ValidDemo {
    @Size(min = 3, max = 12, message = "用户名必须的长度必须是3到12个字母之间")
    @Pattern(regexp = "^[a-z]+$", message = "用户名必须是a-z小字母")
    private String name;

    @Size(min = 6, max = 6, message = "密码必须是6位数字")
    @Pattern(regexp = "^[0-9]+$", message = "密码必须是6位数字")
    private String password;

    @Range(min = 1, max = 9, message = "范围只能1到9")
    private Integer range;

    @NotNull(message = "邮箱不能为Null")
    @Email(regexp = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])",
            message = "邮箱格式有误")
    private String email;

}

web层入参前加上@Valid

@GetMapping("/validdemo")
public Map<String,Object> demo(@Valid ValidDemo validDemo){
    return ApiResultMap.successResult(validDemo);
}

全局处理异常

@ExceptionHandler(value = { BindException.class })
public Map<String, Object> validationException(BindException ex) {
    log.error(ex.getBindingResult().getFieldError().getDefaultMessage());
    return ApiResultMap.errorResult(ex.getBindingResult().getFieldError().getDefaultMessage());
}
2)入参为单数据类型

配置 MethodValidationPostProcessor

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
  return new MethodValidationPostProcessor();
}

web层加上注解

@Validated
@RestController
public class DemoController {}

方法上加上校验

@GetMapping("/validdemo3")
public Map<String,Object> demo3(@NotNull String str, @NotNull @Range(min = 0, max = 10) Integer a){
    return ApiResultMap.successResult(str + a);
}

全局异常校验

/**
* 参数校验报错异常
*/
@ExceptionHandler(ConstraintViolationException.class)
public AjaxResult constraintViolationException(ConstraintViolationException e) {
  String message = e.getMessage();
  String substring = message.substring(message.indexOf(".") + 1);
  return AjaxResult.error(substring.replace(": ", ""));
}

 

 

__EOF__


本文作者五香麻辣大白兔
本文链接:https://www.cnblogs.com/51bishe/p/15128122.html


相关教程