JSR303校驗
統一校驗的需求
前端請求后端接口傳輸參數,是在controller中校驗還是在Service中校驗?
答案是都需要校驗,只是分工不同。
Contoller中校驗請求參數的合法性,包括:必填項校驗,數據格式校驗,比如:是否是符合一定的日期格式,等。
Service中要校驗的是業務規則相關的內容,比如:課程已經審核通過所以提交失敗。
Service中根據業務規則去校驗不方便寫成通用代碼,Controller中則可以將校驗的代碼寫成通用代碼。
早在JavaEE6規范中就定義了參數校驗的規范,它就是JSR-303,它定義了BeanValidation,即對bean屬性進行校
驗。
SpringBoot提供了JSR-303的支持,它就是spring-boot-starter-validation,它的底層使用HibernateValidator,
HibernateValidator是BeanValidation的參考實現。
所以,我們準備在Controller層使用spring-boot-starter-validation完成對請求參數的基本合法性進行校驗。
if校驗
@Transactional
@Override
public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {// 參數合法性校驗if (StringUtils.isBlank(addCourseDto.getName())) {// throw new RuntimeException("課程名稱為空");XueChengPlusException.cast("課程名稱為空");}if (StringUtils.isBlank(addCourseDto.getMt())) {throw new RuntimeException("課程分類為空");}if (StringUtils.isBlank(addCourseDto.getSt())) {throw new RuntimeException("課程分類為空");}if (StringUtils.isBlank(addCourseDto.getGrade())) {throw new RuntimeException("課程等級為空");}if (StringUtils.isBlank(addCourseDto.getTeachmode())) {throw new RuntimeException("教育模式為空");}if (StringUtils.isBlank(addCourseDto.getUsers())) {throw new RuntimeException("適應人群為空");}if (StringUtils.isBlank(addCourseDto.getCharge())) {throw new RuntimeException("收費規則為空");}// 向課程基本信息表course_base插入數據CourseBase courseBase = new CourseBase();BeanUtils.copyProperties(addCourseDto, courseBase);courseBase.setCompanyId(companyId);courseBase.setCreateDate(LocalDateTime.now());// 審核狀態默認為未提交courseBase.setAuditStatus("202002");// 發布狀態為未發布courseBase.setStatus("203001");int insert = courseBaseMapper.insert(courseBase);if (insert <= 0) {throw new RuntimeException("添加課程失敗");}// 向課程營銷系course_market寫入數據CourseMarket courseMarket = new CourseMarket();BeanUtils.copyProperties(addCourseDto, courseMarket);// 主鍵的課程idcourseMarket.setId(courseBase.getId());saveCourseMarket(courseMarket);// 從數據庫查詢課程的詳細信息,包括兩部分return getCourseBaseInfo(courseBase.getId());
}
@Validated注解校驗
依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
定義校驗
package com.xuecheng.content.model.dto;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.math.BigDecimal;/*** @author Mr.M* @version 1.0* @description 添加課程dto* @date 2022/9/7 17:40*/
@Data
@ApiModel(value = "AddCourseDto", description = "新增課程基本信息")
public class AddCourseDto {@NotEmpty(message = "課程名稱不能為空")@ApiModelProperty(value = "課程名稱", required = true)private String name;@NotEmpty(message = "適用人群不能為空")@Size(message = "適用人群內容過少", min = 10)@ApiModelProperty(value = "適用人群", required = true)private String users;@ApiModelProperty(value = "課程標簽")private String tags;@NotEmpty(message = "課程分類不能為空")@ApiModelProperty(value = "大分類", required = true)private String mt;@NotEmpty(message = "課程分類不能為空")@ApiModelProperty(value = "小分類", required = true)private String st;@NotEmpty(message = "課程等級不能為空")@ApiModelProperty(value = "課程等級", required = true)private String grade;@ApiModelProperty(value = "教學模式(普通,錄播,直播等)", required = true)private String teachmode;@ApiModelProperty(value = "課程介紹")@Size(message = "課程描述內容過少", min = 10)private String description;@ApiModelProperty(value = "課程圖片", required = true)private String pic;@NotEmpty(message = "收費規則不能為空")@ApiModelProperty(value = "收費規則,對應數據字典", required = true)private String charge;@ApiModelProperty(value = "價格")private Float price;@ApiModelProperty(value = "原價")private Float originalPrice;@ApiModelProperty(value = "qq")private String qq;@ApiModelProperty(value = "微信")private String wechat;@ApiModelProperty(value = "電話")private String phone;@ApiModelProperty(value = "有效期")private Integer validDays;
}
@Validated 激活校驗
@ApiOperation("新增課程")
@PostMapping("course")
public CourseBaseInfoDto createCourseBase(@RequestBody @Validated AddCourseDto addCourseDto) {// 獲取到用戶所屬機構idLong companyId = 1232141425L;int i = 1/0;return courseBaseInfoService.createCourseBase(companyId, addCourseDto);
}
分組校驗
當多個接口使用同一個模型類的時候,當多個接口對校驗的需求不一樣,這個時候采用分組校驗
用于分級校驗,定義一些常用的組
package com.xuecheng.base.execption;/*** @program: xuecheng-plus-project* @since: jdk1.8* @description: 用于分級校驗,定義一些常用的組* @author: Administrator* @create: 2025-04-29 21:55**/
public class ValidationGroups {public interface Insert {}public interface Update {}public interface Delete {}
}
dto

CourseBaseInfoController

校驗規則不滿足?
如果javax.validation.constraints包下的校驗規則滿足不了需求怎么辦?
1、手寫校驗代碼。
2、自定義校驗規則注解。
如何自定義校驗規則注解,請自行查閱資料實現。
面試
請求參數的合法性校驗如何做?
使用基于JSR303的校驗框架實現,SpringBoot提供了JSR-303的支持,它就是spring-boot-starter-valiqation,它
包括了很多校驗規則,只需要在模型類中通過注解指定校驗規則,在controller方法上開啟校驗。