Spring Boot中如何处理原本标注POST的控制器接口收到的GET请求?
Spring Boot GET请求访问POST限定接口的处理方案
现有代码中
TestController类上的@RequestMapping(value = "/abc", method = RequestMethod.POST)已经限定了该类下所有接口仅匹配POST方法的/abc路径请求,默认情况下GET方法请求该路径时,Spring会直接返回405 Method Not Allowed错误,不会进入该Controller的处理逻辑。
你可以根据实际业务需求选择以下处理方案:
场景1:需要支持GET方法访问/abc接口
- 直接修改类上的@RequestMapping注解,扩展支持的请求方法:
// 同时支持POST和GET方法 @RequestMapping(value = "/abc", method = {RequestMethod.POST, RequestMethod.GET}) public class TestController { // 原有POST逻辑不变,如果GET和POST处理逻辑不同,可以单独加GET处理方法 @GetMapping public String handleGet() { // 编写GET请求的处理逻辑 return "getResult"; } }
- 也可以拆分路径注解,类上只保留路径配置,具体方法上单独指定请求方式:
@RequestMapping("/abc") public class TestController { @PostMapping public String handlePost() { // 原有POST逻辑 } @GetMapping public String handleGet() { // 新增GET逻辑 } }
场景2:不需要支持GET,仅自定义错误返回提示
如果不想允许GET方法访问,又不需要Spring默认的错误页/错误响应,可以全局捕获请求方法不支持的异常,自定义返回格式:
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ResponseEntity<Map<String, Object>> handleMethodNotAllowed(HttpRequestMethodNotSupportedException e) { Map<String, Object> result = new HashMap<>(); result.put("code", 405); result.put("message", "请求方法不合法,该接口仅支持" + Arrays.toString(e.getSupportedMethods()) + "请求"); return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(result); } }
注意事项
按照REST接口设计规范,GET请求为幂等请求,一般用于数据查询,POST用于数据提交,两类请求的业务语义不同,建议不要混用处理逻辑,避免出现重复提交等业务异常
内容的提问来源于stack exchange,提问作者Abhishek Patel
相关产品推荐
相关产品推荐

