How to use @RequestBody with a JSONP request?

梦想与她 提交于 2020-01-01 17:05:24

问题


I am trying to perform an ajax request using the jsonp data type due to cross domain issues in a clustered environment.

I can make jsonp requests to methods mapped with no @RequestBody parameters, but when I do try to implement a RequestMapping with a @RequestBody parameter I get a 415 Unsupported Media Type error.

Usually when I get this problem it is due to some property not mapping correctly between the json object posted and the Java object it is mapped to in Spring. But the only discrepency I can find is that using jsonp it adds a parm named callback and one with the name of an underscore "_"

So I added the tag @JsonIgnoreProperties(ignoreUnknown = true) to my Java object and figured that should solve that, however it is still throwing this error.

Is there anything else I need to do?

EDIT: I am now seeing this stack trace in the debug log output from Spring: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported

$.ajax({
  url : 'http://blah/blah.html',
  data : { abc : '123' }, (I also tried to JSON.stringify the object but no difference)
  dataType : 'jsonp',
  success : function(response) {
    alert('ok '+JSON.stringify(response));
  },
  fail : function(response) { 
    alert('error'+JSON.stringify(response));
  }
});

The Spring controller is:

@RequestMapping({ "blah/blah" })
@ResponseBody
public ReturnObject getBlahBlah (@RequestBody MyObject obj) throws Exception {

    }

The parameter object is:

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {

  private String abc;
  // getter and setter for abc auto generated by MyEclipse
}

I have a breakpoint on the Controller method which is never hit.


回答1:


JSONP means that jQuery will create a <script> element with src pointing to your controller URL.

As you can see, this approach doesn't allow you to pass any data in request body, all data should be passed in URL as query parameters. data : { abc : '123' } means that abc=123 is added to the URL.

At controller side you need to use either @RequestParam (to bind inidividual parameters) or @ModelAttribute (to bind multiple parameters into an object):

public ReturnObject getBlahBlah (@RequestParam("abc") int abc) throws Exception { ... }


来源:https://stackoverflow.com/questions/18301743/how-to-use-requestbody-with-a-jsonp-request

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