You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中@Pattern注解校验如何返回自定义提示信息?

解决Spring Boot表单校验自定义提示不返回问题

要让系统返回你在@Pattern中定义的自定义提示,需要完成以下两步:

1. 确保Controller触发参数校验

在接收SearchCriteria参数的Controller方法上,必须添加@Valid(或@Validated)注解,否则校验规则不会生效。示例代码:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;

@RestController
public class SearchController {

    @PostMapping("/v1/list")
    public String search(@Valid @RequestBody SearchCriteria criteria) {
        // 业务逻辑实现
        return "success";
    }
}

2. 自定义全局异常处理器捕获校验错误

Spring Boot默认的异常处理不会返回校验的详细错误信息,需要自己实现全局异常处理器,捕获MethodArgumentNotValidException并提取自定义提示:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}

效果示例

当输入无效日期格式时,返回的响应会变成:

{
  "from": "Invalid date format",
  "to": "Invalid date format"
}

你也可以根据需求调整响应体的结构,比如统一包装成包含状态码、提示信息的格式。

内容的提问来源于stack exchange,提问作者Neslihan Bozer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:45:51