Can Spring MVC handle requests from HTML forms other than POST and GET?
Asked Answered
P

1

10

Spring 3 MVC supports all 4 of RESTful methods: GET, POST, PUT and DELETE. But does its view technology support them on forms? If not, what is the real use of method attribute in form:form tag?

I tried to use PUT method on the form:

<form:form action="/myaction" method="PUT">
   ...
</form:form>

Generated HTML was:

<form id="command" action="/myaction" method="post">
   <input type="hidden" name="_method" value="PUT"/>
   ...
</form>

It is clear since most browsers don't support other methods besides GET and POST. But Spring can handle it with additional input with name _method and value METHOD_NAME. Does it?

When I send specified form to a controller method annotated with

@RequestMapping(method=RequestMethod.PUT)

it claims, that request method POST is not supported. But why POST and not PUT? What actually happens under the hoods?

Poler answered 6/12, 2010 at 2:54 Comment(0)
V
18

The use of the "hidden parameter" called _method is not specific to Spring MVC's tag library, but is also used by a few other client frameworks. Spring is just following the convention, such as it is.

In order to use this properly, you need to add a filter to your web.xml, (HiddenHttpMethodFilter, see javadoc), which turns the _method parameter into a "real" HTTP method representation in the HttpServletRequest. This is done as a filter to emphasise the fact the the lack of PUT and DELETE is a browser problem - the servlet API supports it just fine.

So if you want to use these methods in your form, you need to add that filter.

P.S. The reason you get the "POST not supported" message is that your form uses POST, and your handler is annotated with PUT, so it doesn't match. Because you don't have the filter defined, the _method parameter is ignored.

Venterea answered 6/12, 2010 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.