欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > SpringBoot参数校验拦截

SpringBoot参数校验拦截

2025/3/18 17:09:48 来源:https://blog.csdn.net/weixin_60523038/article/details/146255867  浏览:    关键词:SpringBoot参数校验拦截

文章目录

目录

文章目录

一、使用步骤

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;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词