IT评测·应用市场-qidao123.com

标题: 如何实现 Java SpringBoot 自动验证入参数据的有效性 [打印本页]

作者: 缠丝猫    时间: 2023-4-13 13:38
标题: 如何实现 Java SpringBoot 自动验证入参数据的有效性
Java SpringBoot 通过javax.validation.constraints下的注解,实现入参数据自动验证
如果碰到 @NotEmpty  否则不生效,注意看下 @RequestBody 前面是否加上了@Valid
Validation常用注解汇总

Constraint详细信息@Null被注释的元素必须为 null@NotNull被注释的元素必须不为 null@NotBlank被注释的元素不能为空(空格视为空)@NotEmpty被注释的元素不能为空 (允许有空格)@Size(max, min)被注释的元素的大小必须在指定的范围内@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@Pattern(value)被注释的元素必须符合指定的正则表达式@DecimalMin(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@DecimalMax(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@AssertTrue被注释的元素必须为 true@AssertFalse被注释的元素必须为 false@Digits (integer, fraction)被注释的元素必须是一个数字,其值必须在可接受的范围内@Past被注释的元素必须是一个过去的日期@Future被注释的元素必须是一个将来的日期示例
  1. /**
  2.    * 用户名
  3.    */
  4.   @NotBlank(message = "用户名不能为空")
  5.   private String username;
  6.   /**
  7.    * 用户真实姓名
  8.    */
  9.   @NotBlank(message = "用户真实姓名不能为空")
  10.   private String name;
  11.   /**
  12.    * 密码
  13.    */
  14.   @Pattern(regexp = "^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]))(?=^[^\\u4e00-\\u9fa5]{0,}$).{8,20}$", message = "密码过于简单有被盗风险,请保证密码大于8位,并且由大小写字母、数字,特殊符号组成")  
  15.   private String password;
  16.   /**
  17.    * 邮箱
  18.    */
  19.   @NotBlank(message = "邮箱不能为空")
  20.   @Email(message = "邮箱格式不正确")
  21.   private String email;
  22.   /**
  23.    * 手机号
  24.    */
  25.   @NotBlank(message = "手机号不能为空")
  26.   @Pattern(regexp = "^(1[0-9])\\d{9}$", message = "手机号格式不正确")
  27.   private String mobile;
复制代码
Demo

入参对象上,添加注解及说明
  1. package com.vipsoft.web.entity;
  2. import javax.validation.constraints.NotBlank;
  3. import javax.validation.constraints.Size;
  4. import java.io.Serializable;
  5. /**
  6. * 定时任务调度
  7. */
  8. public class QuartzJob implements Serializable {
  9.     private static final long serialVersionUID = 1L;
  10.     /**
  11.      * 任务序号
  12.      */
  13.     private long jobId;
  14.     /**
  15.      * 任务名称
  16.      */
  17.     @NotBlank(message = "任务名称不能为空")
  18.     @Size(max = 10, message = "任务名称不能超过10个字符")
  19.     private String jobName;
  20.     /**
  21.      * 任务组名
  22.      */
  23.     @NotBlank(message = "任务组名不能为空")
  24.     @Size(max = 10, message = "任务组名不能超过10个字符")
  25.     private String jobGroup;
  26.     /**
  27.      * 调用目标字符串
  28.      */
  29.     private String invokeTarget;
  30.     /**
  31.      * 执行表达式
  32.      */
  33.     private String cronExpression;
  34.     /**
  35.      * cron计划策略 0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行
  36.      */
  37.     private String misfirePolicy = "0";
  38.     /**
  39.      * 并发执行 0=允许,1=禁止
  40.      */
  41.     private String concurrent;
  42.     /**
  43.      * 任务状态(0正常 1暂停)
  44.      */
  45.     private String status;
  46.     /**
  47.      * 备注
  48.      */
  49.     private String remark;
  50. }
复制代码
Controller @RequestBody 前面必须加上 @Valid 否则不生效
  1. import javax.validation.Valid;
  2. @RestController
  3. @RequestMapping("schedule")
  4. public class ScheduleController {
  5.     private Logger logger = LoggerFactory.getLogger(ScheduleController.class);
  6.     @Autowired
  7.     IQuartzJobService jobService;
  8.     @RequestMapping("/add")
  9.     public ApiResult addTask(@Valid @RequestBody QuartzJob param) throws Exception {
  10.         logger.info("添加调度任务 => {} ", JSONUtil.toJsonStr(param));
  11.         
  12.         return new ApiResult("添加成功");
  13.     }
  14. }
复制代码
异常处理,统一返回对象,方便前端解析
GlobalExceptionHandler
  1. package com.vipsoft.web.exception;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.vipsoft.web.utils.ApiResult;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.validation.BindException;
  7. import org.springframework.validation.BindingResult;
  8. import org.springframework.validation.FieldError;
  9. import org.springframework.validation.ObjectError;
  10. import org.springframework.web.HttpRequestMethodNotSupportedException;
  11. import org.springframework.web.bind.MethodArgumentNotValidException;
  12. import org.springframework.web.bind.annotation.ExceptionHandler;
  13. import org.springframework.web.bind.annotation.RestControllerAdvice;
  14. import java.util.List;
  15. /**
  16. * 全局异常处理器
  17. */
  18. @RestControllerAdvice
  19. public class GlobalExceptionHandler {
  20.     private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  21.     /**
  22.      * 处理自定义异常
  23.      */
  24.     @ExceptionHandler(CustomException.class)
  25.     public ApiResult handleException(CustomException e) {
  26.         // 打印异常信息
  27.         logger.error("### 异常信息:{} ###", e.getMessage());
  28.         return new ApiResult(e.getCode(), e.getMessage());
  29.     }
  30.     /**
  31.      * 参数错误异常
  32.      */
  33.     @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
  34.     public ApiResult handleException(Exception e) {
  35.         if (e instanceof MethodArgumentNotValidException) {
  36.             MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
  37.             BindingResult result = validException.getBindingResult();
  38.             StringBuffer errorMsg = new StringBuffer();
  39.             if (result.hasErrors()) {
  40.                 List<ObjectError> errors = result.getAllErrors();
  41.                 errors.forEach(p -> {
  42.                     FieldError fieldError = (FieldError) p;
  43.                     errorMsg.append(fieldError.getDefaultMessage()).append(",");
  44.                     logger.error("### 请求参数错误:{" + fieldError.getObjectName() + "},field{" + fieldError.getField() + "},errorMessage{" + fieldError.getDefaultMessage() + "}");
  45.                 });
  46.                 return new ApiResult(6001, errorMsg.toString());
  47.             }
  48.         } else if (e instanceof BindException) {
  49.             BindException bindException = (BindException) e;
  50.             if (bindException.hasErrors()) {
  51.                 logger.error("### 请求参数错误: {}", bindException.getAllErrors());
  52.             }
  53.         }
  54.         return new ApiResult(6001, "参数无效");
  55.     }
  56.     /**
  57.      * 处理HttpRequestMethodNotSupporte异常
  58.      * @param e
  59.      * @return
  60.      */
  61.     @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  62.     public Object methodHandler(HttpRequestMethodNotSupportedException e) {
  63.         // 打印异常信息
  64.         logger.error("### 异常信息:{} ###", e.getMessage());
  65.         return new ApiResult(6000, e.getMessage());
  66.     }
  67.     /**
  68.      * 处理所有不可知的异常
  69.      */
  70.     @ExceptionHandler(Exception.class)
  71.     public ApiResult handleOtherException(Exception e) {
  72.         // 打印异常信息
  73.         logger.error("### 系统内部错误:{} ###", e.getMessage(), e);
  74.         String warnMsg = StrUtil.isEmpty(e.getMessage()) ? "### 系统内部错误 ###" : e.getMessage();
  75.         return new ApiResult(6000, "系统内部错误", e.getMessage());
  76.     }
  77. }
复制代码
统一返回对像 ApiResult
  1. package com.vipsoft.web.utils;
  2. //import com.github.pagehelper.PageInfo;
  3. import java.io.Serializable;
  4. public class ApiResult implements Serializable {
  5.     /**
  6.      * 返回编码 0:失败、1:成功
  7.      */
  8.     private int code;
  9.     /**
  10.      * 返回消息
  11.      */
  12.     private String message;
  13.     /**
  14.      * 返回对象
  15.      */
  16.     private Object data;
  17.     /**
  18.      * 分页对象
  19.      */
  20.     private Page page;
  21.     public ApiResult() {
  22.         this.code = 1;
  23.         this.message = "请求成功";
  24.     }
  25.     public ApiResult(Integer code, String message) {
  26.         this.code = code;
  27.         this.message = message;
  28.     }
  29.     public ApiResult(Integer code, String message, Object data) {
  30.         this.code = code;
  31.         this.message = message;
  32.         this.setData(data);
  33.     }
  34.     public ApiResult(Object data) {
  35.         this.code = 1;
  36.         this.message = "请求成功";
  37.         this.setData(data);
  38.     }
  39. //    public ApiResult(PageInfo pageInfo) {
  40. //        this.code = 1;
  41. //        this.message = "请求成功";
  42. //        this.setData(pageInfo.getList());
  43. //        this.setPage(convertToPage(pageInfo));
  44. //    }
  45. //
  46. //    public Page convertToPage(PageInfo pageInfo) {
  47. //        Page result = new Page();
  48. //        result.setTotalCount(pageInfo.getTotal());
  49. //        result.setPageNum(pageInfo.getPageNum());
  50. //        result.setPageCount(pageInfo.getPages());
  51. //        result.setPageSize(pageInfo.getPageSize());
  52. //        result.setPrePage(pageInfo.getPrePage());
  53. //        result.setNextPage(pageInfo.getNextPage());
  54. //        return result;
  55. //    }
  56.     public int getCode() {
  57.         return code;
  58.     }
  59.     public void setCode(int code) {
  60.         this.code = code;
  61.     }
  62.     public String getMessage() {
  63.         return message;
  64.     }
  65.     public void setMessage(String message) {
  66.         this.message = message;
  67.     }
  68.     public Object getData() {
  69.         return data;
  70.     }
  71.     public void setData(Object data) {
  72.         this.data = data;
  73.     }
  74.     public Page getPage() {
  75.         return page;
  76.     }
  77.     public void setPage(Page page) {
  78.         this.page = page;
  79.     }
  80. }
复制代码
运行结果如下


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4