spring Boot - "status":405,"error":"Method not Allowed"

Yog*_*kar 5 java spring-boot

我使用该指南创建了一个简单的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并使用启动Tomcat mvn spring-boot:run.

该指南说默认允许所有HTTP方法.那么为什么它会回应不支持POST?

在POST到此URL时,如何让Spring调用控制器方法?

whi*_*mot 8

正如Spring REST指南中所述,

@RequestMapping 默认情况下映射所有HTTP操作

但是,正如他们建议的那样,你添加了一个允许的http方法的规范:

@RequestMapping(method=GET)

然后只允许GET.POST将被禁止.

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

@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));
}
Run Code Online (Sandbox Code Playgroud)

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

swsmmaRequestMappingHandlerMapping:将"{[/ greeting],methods = [GET || POST]}"映射到公共hello.Greeting hello.GreetingController.greeting(java.lang.String)

另外,你是如何发布的?我可以为Google Chrome 推荐高级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
Run Code Online (Sandbox Code Playgroud)

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

RequestMappingHandlerMapping:查找路径/问候的处理程序方法RequestMappingHandlerMapping:找不到[/ greetings]的处理程序方法