【问题标题】:spring Boot -"status":405,"error":"Method Not Allowed" [closed]spring Boot -“状态”:405,“错误”:“方法不允许”[关闭]
【发布时间】:2016-01-23 15:20:25
【问题描述】:

我使用 the guide 创建了一个简单的 Spring Boot REST 服务,当我 POST 到 http://localhost:8080/greeting 时出现以下错误

-"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"请求方法'POST'不支持",

我没有找到有关如何解决该错误的任何信息。我正在使用版本 1.3.2.RELEASE 并使用 mvn spring-boot:run 启动 Tomcat。

该指南说默认情况下允许所有 HTTP 方法。那么为什么它会响应不支持 POST 呢?

当我 POST 到这个 URL 时,如何让 Spring 调用控制器方法?

【问题讨论】:

  • 旁白:您的问题相当稀疏 - 可能是重复的问题会回答它,但如果没有,您会添加更多细节吗?这听起来像是某种路由问题(尽管我不使用 Spring 或 Java)。

标签: java spring-boot


【解决方案1】:

正如Spring REST guide 中所说,

@RequestMapping默认映射所有HTTP操作

但如果按照他们的建议,您添加了允许的 http 方法的规范:

@RequestMapping(method=GET)

那么只有 GET 被允许。 POST 将被禁止。

如果您想同时允许 GET 和 POST,但不允许所有其他 http methods,那么请这样注释您的控制器方法:

@RequestMapping(value = "/greeting", method = {RequestMethod.GET, RequestMethod.POST})
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
    return new Greeting(counter.incrementAndGet(),
                        String.format(template, name));
}

当您启动应用程序时,所有请求处理程序映射都会被注销。您应该会在日志中看到这样的一行(在 IDE 控制台或命令行窗口中):

s.w.s.m.m.a.RequestMappingHandlerMapping : 将“{[/greeting],methods=[GET || POST]}”映射到公共 hello.Greeting hello.GreetingController.greeting(java.lang.String)

另外,你是如何发布的?我可以为 Google Chrome 推荐 Advanced REST 客户端。如果您从浏览器中的表单发布,请尝试按 f12 并检查“网络”选项卡,以检查您发布的内容是否与您认为发布的内容完全相同。

发布到错误的 URL,例如http://localhost:8080/greetings 而不是 http://localhost:8080/greeting 将导致 Method Not Allowed 错误,尽管该错误实际上是 URL 中的拼写错误,而不是 HTTP 方法的选择。

要查看请求处理的更详细日志记录,请在 src/main/java 文件夹旁边创建一个 src/main/resources 文件夹,然后创建一个 application.properties 文件。将此行添加到该文件中

logging.level.org.springframework.web=DEBUG

然后,如果您尝试 POST 到未映射的 URL,例如/greetings 而不是 /greeting,您会在日志中看到这些行:

RequestMappingHandlerMapping : 查找路径 /greetings 的处理程序方法 RequestMappingHandlerMapping : 没有找到 [/greetings] 的处理方法

【讨论】:

  • 我添加了这个,仍然收到 WARN 885 --- [nio-8080-exec-1] os.web.servlet.PageNotFound : Request method 'POST' not supported
  • @whistling-marmot,感谢您的回复,但仍然无法正常工作
  • 尝试使用stackoverflow.com/questions/22847775/…,但它不起作用。
  • 仅仅让 POST 请求与 Spring Boot 一起工作太难了!!!
  • 感谢您的回复,它现在可以工作了,虽然我不知道上次到底是什么问题..
猜你喜欢
  • 1970-01-01
  • 2013-10-09
  • 2021-09-19
  • 1970-01-01
  • 2017-06-15
  • 2020-08-12
  • 1970-01-01
  • 2018-09-08
  • 2021-12-20
相关资源
最近更新 更多