Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring Boot -"status":405,"error":"Method Not Allowed" [closed]

I created a simple Spring Boot REST service using the guide, and am getting following error when I POST to http://localhost:8080/greeting

-"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported",

I didn't find any info on how to solve the error. I am using version 1.3.2.RELEASE and starting Tomcat using mvn spring-boot:run.

The guide says that all HTTP methods are allowed by default. So why does it respond that POST is not supported?

How can I get Spring to invoke the controller method when I POST to this URL?

like image 500
Yogesh Bedekar Avatar asked Jan 23 '16 15:01

Yogesh Bedekar


1 Answers

As it says in the Spring REST guide,

@RequestMapping maps all HTTP operations by default

but if, as they suggest, you added a specification of the allowable http methods:

@RequestMapping(method=GET)

then only GETs will be allowed. POSTs will be disallowed.

If you want to allow both GET and POST, but disallow all other http methods, then annotate your controller method thusly:

@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));
}

When you start the application, all the request handler mappings are logged out. You should see a line like this in your log (in the IDE console or command line window):

s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting],methods=[GET || POST]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)

Also, how are you POSTing? I can recommend the Advanced REST client for Google Chrome. If you're posting from a form in your browser, try hitting f12 and examining the Network tab to check that you are POSTing exactly what you think you're POSTing.

POSTing to the wrong URL, e.g. http://localhost:8080/greetings instead of http://localhost:8080/greeting will result in a Method Not Allowed error, although really the error is a typo in the URL, not the choice of HTTP method.

To see more detailed logging for the request processing, create a src/main/resources folder alongside your src/main/java folder, and create an application.properties file in there. Add this line to that file

logging.level.org.springframework.web=DEBUG

Then, if you try to POST to an unmapped URL, e.g. /greetings instead of /greeting, you'll see these lines in you log:

RequestMappingHandlerMapping : Looking up handler method for path /greetings RequestMappingHandlerMapping : Did not find handler method for [/greetings]

like image 123
whistling_marmot Avatar answered Nov 06 '22 11:11

whistling_marmot