Java SpringBoot 通過javax.validation.constraints下的注解,實(shí)現(xiàn)入?yún)?shù)據(jù)自動(dòng)驗(yàn)證
如果碰到 @NotEmpty
否則不生效,注意看下 @RequestBody
前面是否加上了@Valid
Validation常用注解匯總
Constraint | 詳細(xì)信息 |
---|---|
@Null | 被注釋的元素必須為 null |
@NotNull | 被注釋的元素必須不為 null |
@NotBlank | 被注釋的元素不能為空(空格視為空) |
@NotEmpty | 被注釋的元素不能為空 (允許有空格) |
@Size(max, min) | 被注釋的元素的大小必須在指定的范圍內(nèi) |
@Min(value) | 被注釋的元素必須是一個(gè)數(shù)字,其值必須大于等于指定的最小值 |
@Max(value) | 被注釋的元素必須是一個(gè)數(shù)字,其值必須小于等于指定的最大值 |
@Pattern(value) | 被注釋的元素必須符合指定的正則表達(dá)式 |
@DecimalMin(value) | 被注釋的元素必須是一個(gè)數(shù)字,其值必須大于等于指定的最小值 |
@DecimalMax(value) | 被注釋的元素必須是一個(gè)數(shù)字,其值必須小于等于指定的最大值 |
@AssertTrue | 被注釋的元素必須為 true |
@AssertFalse | 被注釋的元素必須為 false |
@Digits (integer, fraction) | 被注釋的元素必須是一個(gè)數(shù)字,其值必須在可接受的范圍內(nèi) |
@Past | 被注釋的元素必須是一個(gè)過去的日期 |
@Future | 被注釋的元素必須是一個(gè)將來的日期 |
示例
/**
* 用戶名
*/
@NotBlank(message = "用戶名不能為空")
private String username;
/**
* 用戶真實(shí)姓名
*/
@NotBlank(message = "用戶真實(shí)姓名不能為空")
private String name;
/**
* 密碼
*/
@Pattern(regexp = "^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]))(?=^[^\\u4e00-\\u9fa5]{0,}$).{8,20}$", message = "密碼過于簡(jiǎn)單有被盜風(fēng)險(xiǎn),請(qǐng)保證密碼大于8位,并且由大小寫字母、數(shù)字,特殊符號(hào)組成")
private String password;
/**
* 郵箱
*/
@NotBlank(message = "郵箱不能為空")
@Email(message = "郵箱格式不正確")
private String email;
/**
* 手機(jī)號(hào)
*/
@NotBlank(message = "手機(jī)號(hào)不能為空")
@Pattern(regexp = "^(1[0-9])\\d{9}$", message = "手機(jī)號(hào)格式不正確")
private String mobile;
Demo
入?yún)?duì)象上,添加注解及說明
package com.vipsoft.web.entity;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* 定時(shí)任務(wù)調(diào)度
*/
public class QuartzJob implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 任務(wù)序號(hào)
*/
private long jobId;
/**
* 任務(wù)名稱
*/
@NotBlank(message = "任務(wù)名稱不能為空")
@Size(max = 10, message = "任務(wù)名稱不能超過10個(gè)字符")
private String jobName;
/**
* 任務(wù)組名
*/
@NotBlank(message = "任務(wù)組名不能為空")
@Size(max = 10, message = "任務(wù)組名不能超過10個(gè)字符")
private String jobGroup;
/**
* 調(diào)用目標(biāo)字符串
*/
private String invokeTarget;
/**
* 執(zhí)行表達(dá)式
*/
private String cronExpression;
/**
* cron計(jì)劃策略 0=默認(rèn),1=立即觸發(fā)執(zhí)行,2=觸發(fā)一次執(zhí)行,3=不觸發(fā)立即執(zhí)行
*/
private String misfirePolicy = "0";
/**
* 并發(fā)執(zhí)行 0=允許,1=禁止
*/
private String concurrent;
/**
* 任務(wù)狀態(tài)(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("添加調(diào)度任務(wù) => {} ", JSONUtil.toJsonStr(param));
return new ApiResult("添加成功");
}
}
異常處理,統(tǒng)一返回對(duì)象,方便前端解析
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());
}
/**
* 參數(shù)錯(cuò)誤異常
*/
@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("### 請(qǐng)求參數(shù)錯(cuò)誤:{" + 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("### 請(qǐng)求參數(shù)錯(cuò)誤: {}", bindException.getAllErrors());
}
}
return new ApiResult(6001, "參數(shù)無效");
}
/**
* 處理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("### 系統(tǒng)內(nèi)部錯(cuò)誤:{} ###", e.getMessage(), e);
String warnMsg = StrUtil.isEmpty(e.getMessage()) ? "### 系統(tǒng)內(nèi)部錯(cuò)誤 ###" : e.getMessage();
return new ApiResult(6000, "系統(tǒng)內(nèi)部錯(cuò)誤", e.getMessage());
}
}
統(tǒng)一返回對(duì)像 ApiResult文章來源:http://www.zghlxwxcb.cn/news/detail-412289.html
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;
/**
* 返回對(duì)象
*/
private Object data;
/**
* 分頁對(duì)象
*/
private Page page;
public ApiResult() {
this.code = 1;
this.message = "請(qǐng)求成功";
}
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 = "請(qǐng)求成功";
this.setData(data);
}
// public ApiResult(PageInfo pageInfo) {
// this.code = 1;
// this.message = "請(qǐng)求成功";
// 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 = data;
}
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
}
運(yùn)行結(jié)果如下文章來源地址http://www.zghlxwxcb.cn/news/detail-412289.html
到了這里,關(guān)于如何實(shí)現(xiàn) Java SpringBoot 自動(dòng)驗(yàn)證入?yún)?shù)據(jù)的有效性的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!