开发者

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

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 t开发者_如何学运维he 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜