Spring and ExtJS “400 Bad Request” with PUT but not with POST

蹲街弑〆低调 提交于 2020-01-06 04:30:32

问题


I'm trying to send parameters with PUT from JavaScript to a Spring application. Here is the @RequestMapping in a Spring Controller:

@RequestMapping(value = "toggle-paid-action", method = RequestMethod.PUT)
@ResponseBody
public final String togglePaid(@RequestParam final int year, 
    @RequestParam final String docType, @RequestParam final int number) {

And here the JavaScript snippet that is supposed to send those parameters.

Ext.Ajax.request({
    params: {year: year, docType: docType, number: number},
    url: 'toggle-paid-action',
    method: 'PUT',

However, I get a "400 Bad Request" every time with description "The request sent by the client was syntactically incorrect ()".

If I check with Firebug, there is a PUT tab with all my parameters, and the parameters are correctly spelled since if I switch from PUT to POST on both sides everything works.

I was wondering what could be the problem, is PUT limited to @PathVariable parameters, or it can send also POST-like parameters?


回答1:


I suppose you can't pass parameters to spring using request method PUT as there is a restriction in the servlet API. You can only work with PUT methods implementing a restful service, passing data as the request body, in other cases (like Spring MVC Databinding) PUT won't work. see SpringMVC is not recognizing request body parameters if using PUT

JIRA: https://jira.springsource.org/browse/SPR-7414




回答2:


This, as suggest above, seems to be a bug in spring/servlet API. In reality PUT requests are supposed to work on Request Body (or payload) and not on Request Parameters. In that sense, servlet API & spring's handling is correct.

Having said that, a better and much easier workaround is to pass no data element from your javascript/jQuery call and pass your parameters as part of the url itself. meaning, set parameters in the url field the way you would do in a GET call.

$.ajax({
            url: "yoururl" + "?param1=param2Val&..",
            type: "PUT",
            data: "",
            success: function(response) {
                // ....
            }
     });

now this works for simple parameters, i guess, will not work for complex JSON types. Hope this helps.



来源:https://stackoverflow.com/questions/7372965/spring-and-extjs-400-bad-request-with-put-but-not-with-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!