Skip to content
javahacks.dev
Spring MVC

Fix 405 Method Not Allowed in a Spring MVC Controller

Fix a 405 Method Not Allowed from a Spring MVC endpoint by matching the HTTP verb, the path and redirects that turn a POST into a GET.

6 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring, Spring Boot, Swagger and PostgreSQL logos.

The server log carries the exception:

Text
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' is not supported

and the response has status 405 with a header such as Allow: GET,HEAD. Spring MVC found a handler for the URL and none for the verb. That is already useful: your path is right. The request pipeline is described in how Spring MVC handles a request.

Compare the verb with the mapping

java
@RestController
@RequestMapping("/api/orders")
class OrderController {

    @GetMapping("/{id}")
    OrderView get(@PathVariable long id) { ... }

    @PostMapping
    OrderView create(@RequestBody CreateOrder body) { ... }
}

Here, POST /api/orders/17 returns 405 with Allow: GET,HEAD, because the path /api/orders/{id} exists only for reads. Reading the Allow header answers most cases. The usual reasons are a wrong verb in the client, a missing path variable (so the request hits the collection URL), and an annotation that does not say what you think:

java
@RequestMapping("/{id}")        // no method restriction: matches every verb

Cause: a redirect turned your POST into a GET

This is the least obvious cause and the most common one in deployed systems. A client calls http://api.example.test/orders with a POST. The server or load balancer redirects to https://... with a 301. Most clients follow a 301 or 302 by repeating the request as a GET, dropping the body. The GET lands on a path that has no GET handler, and you see 405. Check the access log: the POST is followed by a GET from the same client. Fix it by calling the HTTPS URL directly, or configure the redirect with 307 or 308, which preserve the method.

Cause: a trailing slash

Since Spring Framework 6, /api/orders/ does not match a mapping for /api/orders. The framework answers 404 for that, but a proxy rewriting paths can produce a different route and a 405. Use the exact path.

Cause: forms and other verbs

HTML forms submit GET or POST only. To reach a PUT or DELETE handler from a form, send POST with a hidden _method field and enable the filter:

properties
spring.mvc.hiddenmethod.filter.enabled=true

For APIs, call from JavaScript with the right verb instead.

Cause: CSRF or security reshaping the request

Spring Security does not turn a POST into a 405; it answers 403. If you see 405 with security enabled, the request still reached MVC, and the cause is in the mapping. A 403 on POST is a different problem, covered in Spring Security 403 on POST.

Return a clearer response

java
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
ResponseEntity<ProblemDetail> wrongMethod(HttpRequestMethodNotSupportedException e) {
    ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.METHOD_NOT_ALLOWED,
            "Method " + e.getMethod() + " is not allowed here.");
    return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED)
            .allow(e.getSupportedHttpMethods().toArray(HttpMethod[]::new)).body(p);
}

Keep the Allow header: HTTP requires it on a 405, and clients use it.

Reproduce it and read the header that explains it

A 405 response carries the answer in a header, and few people look. This controller accepts only POST on /orders. A GET request to the same path gets this, on Spring Boot 4.0.9:

java
@RestController
class OrdersApi {
    @PostMapping("/orders")
    String create() { return "created"; }
}
Text
$ curl -i localhost:8096/orders
HTTP/1.1 405
Allow: POST

$ curl -s -X POST localhost:8096/orders
created

The Allow: POST header is the server telling the client which methods the URL does support. A 405 means "the path exists, the verb does not", which is different from a 404. If your client sends GET and the header says POST, the mismatch is in the request or the mapping. The server log with web logging at debug shows the same fact in words:

Text
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException:
  Request method 'GET' is not supported]

A browser address bar always sends GET, which is why opening a POST-only endpoint in the browser produces this error and not a result. That is a normal 405, not a fault.

Add a method and check the answer

When both verbs should work, map both on purpose. Prefer separate handlers, because a single method that serves GET and POST usually does two jobs.

java
@RestController
@RequestMapping("/orders")
class OrdersApi {

    @GetMapping
    List<OrderView> list() { return orders.recent(); }

    @PostMapping
    ResponseEntity<OrderView> create(@RequestBody NewOrder body) {
        OrderView created = orders.place(body);
        return ResponseEntity.created(URI.create("/orders/" + created.id())).body(created);
    }
}

After the change, curl -i -X OPTIONS lists the supported methods, which is also what a CORS preflight asks. Spring answers OPTIONS automatically for mapped paths, so the response shows the Allow header without any extra code.

Shell
curl -i -X OPTIONS localhost:8080/orders

Test it so it cannot regress

A MockMvc test of the contract documents which verbs are supported, and fails the day a mapping changes by accident.

java
@WebMvcTest(OrdersApi.class)
class OrdersApiTest {

    @Autowired MockMvc mvc;

    @Test
    void getOnAPostOnlyPathIs405WithAllowHeader() throws Exception {
        mvc.perform(get("/orders"))
           .andExpect(status().isMethodNotAllowed())
           .andExpect(header().string("Allow", "POST"));
    }
}

Causes beyond the annotation

The checklist in this post covers the usual non-code causes. A redirect that follows a POST converts it to a GET in browsers for status 301 and 302, so a form that posts to /orders and gets redirected to /orders/ arrives as a GET at a POST-only mapping. Use 307 or 308, which preserve the method, or fix the URL so no redirect happens. A trailing slash is the commonest trigger: Spring Framework 6 and later no longer matches /orders/ to /orders by default, so a client that adds the slash gets a 404 or 405 depending on the other mappings. And a proxy or load balancer that rewrites verbs or blocks PUT and DELETE produces a 405 that never reached the application; if the application log shows no request at all, look at the gateway.

When the error appears only in production, compare a request through the gateway with the same request sent directly to the application's port. If the direct request works, the problem is in the infrastructure between them, and the fix belongs in its configuration, not in the controller.

The 405 that is actually a missing body or content type

Some 405 and 415 responses look alike and have different causes, so check the status number. A 415 means the path and verb matched but the Content-Type is not one the handler consumes, for instance sending form data to a method declared with consumes = "application/json". A 400 means the body could not be parsed. A 405 only ever means that no handler accepts the verb for this path. Send the same request with curl -v and compare the verb, the path and the headers with the mapping, in that order. It is a short list and the answer is on it.

When the application is correct and the client is wrong, make the error easier for the client developer: a custom handler for HttpRequestMethodNotSupportedException can return a problem detail body that lists the supported methods from e.getSupportedHttpMethods().

Where this does not apply

If the status is 404, no path matched, which is a mapping or scanning problem: see Whitelabel Error Page 404. If your CORS preflight returns 405, the browser's OPTIONS request has no handler; fix that in the CORS configuration, as in CORS errors in Spring Boot. The HTTP semantics specification, RFC 9110 defines 405 and the Allow header. The Spring MVC reference documents the behavior in detail.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.