Spring Boot中如何让/v0外的无效URL返回JSON而非HTML
解决Spring Boot上下文路径外请求返回JSON 404的问题
问题原因
你配置了servlet.context-path: /v0后,访问localhost:8080这类根路径时,Spring Boot会优先查找静态资源目录下的index.html并返回,不会触发NoHandlerFoundException,所以你的@ControllerAdvice异常处理器根本没生效。
解决方案
1. 修改配置文件,开启未匹配请求抛出异常
在application.yml(或application.properties)中添加以下配置:
spring: mvc: throw-exception-if-no-handler-found: true web: resources: add-mappings: false
spring.mvc.throw-exception-if-no-handler-found: true:让Spring MVC在找不到请求处理器时抛出NoHandlerFoundExceptionspring.web.resources.add-mappings: false:关闭静态资源的自动映射,避免Spring Boot返回静态资源(比如index.html)
2. 调整异常处理器的返回格式
你的异常处理器返回字段和期望的JSON结构不一致,修改成目标格式:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity<Map<String, Object>> handleNoHandlerFoundException(NoHandlerFoundException e) { Map<String, Object> errorResponse = new LinkedHashMap<>(); // 生成符合要求的ISO8601格式时间戳 errorResponse.put("timestamp", OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); errorResponse.put("status", HttpStatus.NOT_FOUND.value()); errorResponse.put("error", HttpStatus.NOT_FOUND.getReasonPhrase()); errorResponse.put("path", e.getRequestURL()); return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND); } }
3. 验证效果
重启应用后访问localhost:8080,就能得到你期望的JSON格式404响应:
{ "timestamp": "2022-12-01T12:59:51.832+00:00", "status": 404, "error": "Not Found", "path": "/" }
内容的提问来源于stack exchange,提问作者TheDude
相关产品推荐
相关产品推荐

