Recently I’ve started developing a new website utilizing Spring Technologies, Spring MVC and Spring Security. This is best way to learn something new, rather than reading and reading I decided to implement a website with SpringMVC, Spring Security.
As I haven’t done any website with Spring MVC before I struggled a little bit with it.
One of the problems I’ve faced was, the title of this post, Spring MVC HTTP Status 405 – Request method ‘POST’ not supported.
I was implementing the log in page where the users POST their username and password to a spring controller, depending on if username exist and password is correct the controller FORWARDS to index.html or /login.
When the username and password are correct the controller redirects to index.html and then “Spring MVC HTTP Status 405 – Request method ‘POST’ not supported” popped out.
One of the most confusing things I saw when I was searching for a solution was the amount of questions asked on StackOverflow on, the same problem, and that most of them were left with no answer.
So what was really happening ?
When the form is POSTed to its controller and username and password are correct the controller FORWARDS the user to index.html. The default behavior of a Spring MVC controller is to forward the user to the specified view name in the returned string.
However, the index.html was actually mapped as a resource this is done with
ResourceHandlerRegistry this registry registers location of static resources these static resources are served when HTTP GET request is sent. However, HTTP POST request are not supported when requesting resources. But where does POST request come from ? It comes from posting the form, as we stated early, Spring does not redirect to specified view rather it forwards to it. The differences between forward and redirect response are asfollow :
- a forward is performed internally
- the browser is completely unaware that it has taken place, so its original URL remains intact
- any browser reload of the resulting page will simple repeat the original request, with the original URL
- a redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original
- a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
- redirect is marginally slower than a forward, since it requires two browser requests, not one
- objects placed in the original request scope are not available to the second request
This is why I was receiving 405 method not supported when sending forward.
The solution is to send a redirect rather than forward response.
Check the code snippets here