spring boot 处理 405 method not allowed 错误,最直接的方式是注册一个全局异常处理器来捕获 httprequestmethodnotsupportedexception。在配置类或控制器中定义一个使用 @controlleradvice 注解的类,并在其中编写一个使用 @exceptionhandler 的方法专门处理该异常,返回自定义的错误响应体。这样可以将默认的 tomcat 错误页面替换为符合 api 规范的 json 格式。

如何拦截并转换 405 异常为 JSON 响应
通过实现 HandlerExceptionResolver 接口或使用 @RestControllerAdvice 可以统一接管异常逻辑。核心在于识别请求方法不匹配的情况,并构造包含状态码和错误信息的对象。推荐使用 @RestControllerAdvice,因为它能自动将返回值序列化为 JSON,无需手动操作 HttpServletResponse。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<Map<String, Object>> handleMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
Map<String, Object> body = new HashMap<>();
body.put("status", 405);
body.put("error", "Method Not Allowed");
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.METHOD_NOT_ALLOWED);
}
}
上述代码定义了一个全局异常处理器。当 Spring MVC 发现请求的 HTTP 方法(如 POST)与控制器映射的方法(如 GET)不匹配时,会抛出 HttpRequestMethodNotSupportedException。此时,handleMethodNotSupported 方法会被调用,返回一个包含详细信息的 JSON 对象。开发者只需确保项目中引入了 spring-boot-starter-web,该配置即可生效。
如何处理 OPTIONS 预检请求导致的 405
在前端跨域请求中,浏览器会先发送 OPTIONS 请求进行预检。如果后端没有显式处理 OPTIONS 方法,或者 CORS 配置不当,也可能导致 405 错误。除了异常处理,还需要确保控制器支持 OPTIONS 方法或通过 CORS 配置允许该方法。通常,Spring Boot 默认会对静态资源和部分路径启用 CORS,但自定义 Controller 需要明确声明。

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/data")
@CrossOrigin(origins = "*")
public class DataController {
// 显式支持 OPTIONS 以避免预检失败
@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public String getData() {
return "data";
}
}
在控制器级别添加 @CrossOrigin 注解可以简化 CORS 配置。同时,在 @RequestMapping 中显式列出 RequestMethod.OPTIONS 可以确保预检请求被正常响应,而不是抛出 405 异常。这种组合方式能有效解决因跨域预检引发的 405 问题。对于更复杂的场景,可以使用 CorsConfigurationSource Bean 进行全局 CORS 配置,同样需要在配置中允许 OPTIONS 方法。
当请求方法完全未映射时会发生什么
如果请求的 URL 存在,但没有任何 Controller 方法映射到该 URL,或者映射的方法不支持当前 HTTP 动词,Spring Boot 的行为取决于具体的 DispatcherServlet 配置。通常情况下,如果 URL 匹配但方法不匹配,会触发 405;如果 URL 都不匹配,则触发 404。在处理 405 时,需要注意区分这两种情况,因为它们的异常类型不同。405 对应 HttpRequestMethodNotSupportedException,而 404 对应 NoHandlerFoundException。确保异常处理器只针对特定的异常类型,避免误捕其他异常。


















