后端在进行数据请求时,通常会校验前端传递过来的参数是否是空值或者是null。通常会通过if
判断值是否满足条件,不满足就返回。但如果前端传递的是表单,那么要进行判断的条件就比较多了,太多的if
会让代码变得臃肿,而且也不好维护。可以通过今天的验证框架进行参数校验。
- 引入依赖坐标:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- 在需要判断的类的参数上开启条件判断
@NotNull
适用于基本数据类型(Integer,Long,Double等等),当 @NotNull 注解被使用在 String 类型的数据上,则表示该数据不能为 Null(但是可以为 Empty)@NotBlank
适用于 String 类型的数据上,加了@NotBlank 注解的参数不能为 Null 且 trim() 之后 size > 0,必须有实际字符@NotEmpty
适用于 String、Collection集合、Map、数组等等,加了@NotEmpty 注解的参数不能为 Null 或者 长度为 0@Min
使用数字最小值不能小于x@Max
数字最大值不能大于x@Email
字符串为邮件格式@Size
字符串长度最小为x、集合长度最小为x,@Size(min = 2,max = 20,message = "用户名长度要在2-20之间")
@Pattern
正则表达式,@Pattern(regexp="0?1[0-9]{10}",message = "请输入正确的手机号")
@Data
public class MemberRegisterReq {
@Pattern(regexp="0?1[0-9]{10}",message = "请输入正确的手机号")
private String mobile;
@NotBlank(message="用户名不能为空")
@Size(min = 2,max = 20,message = "用户名长度要在2-20之间")
private String username;
@NotEmpty(message = "数组不能为空")
private List<Long> friends;
@NotBlank(message="邮箱不能为空")
@Email(message="邮箱格式不正确")
private String email;
}
- 在controller层通过
@Valid
开启数据校验
@PostMapping("/register")
public CommonResp<Long> register(@Valid MemberRegisterReq req){}
通过上面的操作后就可以完成请求过来时参数校验。
使用一个统一异常处理器来拦截由@Valid 触发的异常信息并返回:
当数据校验出现问题时就会抛出一个MethodArgumentNotValidException
异常,这个异常是
统一异常处理器中可以获取这个异常的信息进行统一信息返回:
package com.lzk.train.common.controller;
import com.lzk.train.common.resp.CommonResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 统一异常处理、数据预处理等
*/
@ControllerAdvice
public class ControllerExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);
/**
* 所有异常统一处理
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public CommonResp exceptionHandler(Exception e) {
CommonResp commonResp = new CommonResp();
LOG.error("系统异常:", e);
commonResp.setSuccess(false);
//当有方法抛出异常时,统一进行异常消息处理,e.getMessage()是业务异常,下面会进行针对异常处理
//commonResp.setMessage(e.getMessage());
//如果出现了这个异常,证明系统有bug
commonResp.setMessage("系统出现异常,请联系管理员");
return commonResp;
}
/**
* 校验异常统一处理
* @param e
* @return
*/
@ExceptionHandler(value = BindException.class)
@ResponseBody
public CommonResp exceptionHandler(BindException e) {
CommonResp commonResp = new CommonResp();
LOG.error("校验异常:{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
commonResp.setSuccess(false);
commonResp.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return commonResp;
}
}