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 | 被注釋的元素必須是一個將來的日期 |
示例
/**
* 用戶名
*/
@NotBlank(message = "用戶名不能為空")
private String username;
/**
* 用戶真實姓名
*/
@NotBlank(message = "用戶真實姓名不能為空")
private String name;
/**
* 密碼
*/
@Pattern(regexp = "^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]))(?=^[^\\u4e00-\\u9fa5]{0,}$).{8,20}$", message = "密碼過于簡單有被盜風險,請保證密碼大于8位,并且由大小寫字母、數字,特殊符號組成")
private String password;
/**
* 郵箱
*/
@NotBlank(message = "郵箱不能為空")
@Email(message = "郵箱格式不正確")
private String email;
/**
* 手機號
*/
@NotBlank(message = "手機號不能為空")
@Pattern(regexp = "^(1[0-9])\\d{9}$", message = "手機號格式不正確")
private String mobile;
Demo
入參物件上,添加注解及說明
package com.vipsoft.web.entity;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* 定時任務調度
*/
public class QuartzJob implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 任務序號
*/
private long jobId;
/**
* 任務名稱
*/
@NotBlank(message = "任務名稱不能為空")
@Size(max = 10, message = "任務名稱不能超過10個字符")
private String jobName;
/**
* 任務組名
*/
@NotBlank(message = "任務組名不能為空")
@Size(max = 10, message = "任務組名不能超過10個字符")
private String jobGroup;
/**
* 呼叫目標字串
*/
private String invokeTarget;
/**
* 執行運算式
*/
private String cronExpression;
/**
* cron計劃策略 0=默認,1=立即觸發執行,2=觸發一次執行,3=不觸發立即執行
*/
private String misfirePolicy = "0";
/**
* 并發執行 0=允許,1=禁止
*/
private String concurrent;
/**
* 任務狀態(0正常 1暫停)
*/
private String status;
/**
* 備注
*/
private String remark;
}
Controller @RequestBody 前面必須加上 @Valid 否則不生效
import javax.validation.Valid;
@RestController
@RequestMapping("schedule")
public class ScheduleController {
private Logger logger = LoggerFactory.getLogger(ScheduleController.class);
@RequestMapping("/add")
public ApiResult addTask(@Valid @RequestBody QuartzJob param) throws Exception {
logger.info("添加調度任務 => {} ", JSONUtil.toJsonStr(param));
return new ApiResult("添加成功");
}
}
例外處理,統一回傳物件,方便前端決議
GlobalExceptionHandler
package com.vipsoft.web.exception;
import cn.hutool.core.util.StrUtil;
import com.vipsoft.web.utils.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
/**
* 全域例外處理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 處理自定義例外
*/
@ExceptionHandler(CustomException.class)
public ApiResult handleException(CustomException e) {
// 列印例外資訊
logger.error("### 例外資訊:{} ###", e.getMessage());
return new ApiResult(e.getCode(), e.getMessage());
}
/**
* 引數錯誤例外
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
public ApiResult handleException(Exception e) {
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
BindingResult result = validException.getBindingResult();
StringBuffer errorMsg = new StringBuffer();
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
errors.forEach(p -> {
FieldError fieldError = (FieldError) p;
errorMsg.append(fieldError.getDefaultMessage()).append(",");
logger.error("### 請求引數錯誤:{" + fieldError.getObjectName() + "},field{" + fieldError.getField() + "},errorMessage{" + fieldError.getDefaultMessage() + "}");
});
return new ApiResult(6001, errorMsg.toString());
}
} else if (e instanceof BindException) {
BindException bindException = (BindException) e;
if (bindException.hasErrors()) {
logger.error("### 請求引數錯誤: {}", bindException.getAllErrors());
}
}
return new ApiResult(6001, "引數無效");
}
/**
* 處理HttpRequestMethodNotSupporte例外
* @param e
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Object methodHandler(HttpRequestMethodNotSupportedException e) {
// 列印例外資訊
logger.error("### 例外資訊:{} ###", e.getMessage());
return new ApiResult(6000, e.getMessage());
}
/**
* 處理所有不可知的例外
*/
@ExceptionHandler(Exception.class)
public ApiResult handleOtherException(Exception e) {
// 列印例外資訊
logger.error("### 系統內部錯誤:{} ###", e.getMessage(), e);
String warnMsg = StrUtil.isEmpty(e.getMessage()) ? "### 系統內部錯誤 ###" : e.getMessage();
return new ApiResult(6000, "系統內部錯誤", e.getMessage());
}
}
統一回傳對像 ApiResult
package com.vipsoft.web.utils;
//import com.github.pagehelper.PageInfo;
import java.io.Serializable;
public class ApiResult implements Serializable {
/**
* 回傳編碼 0:失敗、1:成功
*/
private int code;
/**
* 回傳訊息
*/
private String message;
/**
* 回傳物件
*/
private Object data;
/**
* 分頁物件
*/
private Page page;
public ApiResult() {
this.code = 1;
this.message = "請求成功";
}
public ApiResult(Integer code, String message) {
this.code = code;
this.message = message;
}
public ApiResult(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.setData(data);
}
public ApiResult(Object data) {
this.code = 1;
this.message = "請求成功";
this.setData(data);
}
// public ApiResult(PageInfo pageInfo) {
// this.code = 1;
// this.message = "請求成功";
// this.setData(pageInfo.getList());
// this.setPage(convertToPage(pageInfo));
// }
//
// public Page convertToPage(PageInfo pageInfo) {
// Page result = new Page();
// result.setTotalCount(pageInfo.getTotal());
// result.setPageNum(pageInfo.getPageNum());
// result.setPageCount(pageInfo.getPages());
// result.setPageSize(pageInfo.getPageSize());
// result.setPrePage(pageInfo.getPrePage());
// result.setNextPage(pageInfo.getNextPage());
// return result;
// }
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = https://www.cnblogs.com/vipsoft/p/data;
}
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
}
運行結果如下

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549947.html
標籤:Java
