2026-10-30 18:03:59
在Spring Boot中统一处理GET和POST请求参数校验,可通过封装DTO对象和自定义全局异常处理器实现。以下是具体方案:
1. 封装请求参数为DTO对象示例代码:
// GET请求参数封装@GetMapping("/api")public String apiGet(@Valid ApiGetRequest request) { // 处理逻辑}public class ApiGetRequest { @NotNull(message = "feedId不能为空") private Long feedId; // getters和setters}将GET请求的单个参数(如feedId)封装为DTO对象(如ApiGetRequest)。
在DTO属性上添加JSR-303校验注解(如@NotNull),并指定错误消息。
通过@ControllerAdvice捕获校验异常,统一返回格式化的错误信息。
示例代码:
@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler({MethodArgumentNotValidException.class, MissingServletRequestParameterException.class}) @ResponseBody public ResponseEntity<Map<String, String>> handleValidationExceptions(Exception ex) { Map<String, String> errorResponse = new HashMap<>(); String errorMessage; if (ex instanceof MethodArgumentNotValidException) { MethodArgumentNotValidException e = (MethodArgumentNotValidException) ex; errorMessage = e.getBindingResult().getFieldError().getDefaultMessage(); } else if (ex instanceof MissingServletRequestParameterException) { MissingServletRequestParameterException e = (MissingServletRequestParameterException) ex; errorMessage = "校验失败: " + e.getParameterName() + " 不能为空"; } else { errorMessage = "未知错误"; } errorResponse.put("error", errorMessage); return ResponseEntity.badRequest().body(errorResponse); }}捕获MethodArgumentNotValidException(POST校验失败)和MissingServletRequestParameterException(GET参数缺失)。
提取异常信息并封装为统一格式(如Map<String, String>)。
返回ResponseEntity,设置HTTP状态码为400 Bad Request。
通过封装DTO对象和自定义全局异常处理器,Spring Boot可统一处理GET和POST请求的参数校验,返回格式一致的错误信息。此方案兼顾了校验的严格性和代码的简洁性,适用于大多数Web应用场景。