开发者

Spring and ExtJS "400 Bad Request" with PUT but not with POST

开发者 https://www.devze.com 2023-04-04 04:07 出处:网络
I\'m trying to send parameters with PUT from JavaScript to a Spring application. Here is the @RequestMapping in a Spring Controller:

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 in开发者_Go百科correct ()".

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?


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


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.

0

精彩评论

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