文章目录
目录
文章目录
一、使用步骤
1.引入库
2.参数校验
3.参数拦截
4.拦截参数校验
一、使用步骤
1.引入库
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId> </dependency>
2.参数校验
代码如下(示例):
@TableField(exist = false)private static final long serialVersionUID = 1L;/*** 模型名称*/@NotBlank(message = "模型名称不能为空")@Size(min = 3, max = 30, message = "模型名称长度在3-30之间")private String modelName;/*** 客户端名称*/@NotBlank(message = "客户端名称不能为空")@Size(min = 3, max = 30, message = "客户端名称长度在3-30之间")private String clientName;
3.参数拦截
/*** 处理参数校验异常*/@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})public BaseResponse<?> handleValidationExceptions(Exception e) {log.error("参数校验异常", e);String message;if (e instanceof MethodArgumentNotValidException validException) {message = validException.getBindingResult().getAllErrors().get(0).getDefaultMessage();} else {BindException bindException = (BindException) e;message = bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage();}return ResultUtils.error(ErrorCode.PARAMS_ERROR, message);}/*** 处理JSON解析异常*/@ExceptionHandler(HttpMessageNotReadableException.class)public BaseResponse<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {log.error("JSON解析异常", e);return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求参数格式错误");}
4.拦截参数校验
主要是添加@Valid这个注解之后就可以进行参数拦截了
public BaseResponse<Integer> addModel(@Valid @RequestBody AddAiModelDTO addAiModelDTO) {log.info("接收到添加模型请求: {}", addAiModelDTO);return null;}