Spring 4: MappingJackson2HttpMessageConverter does not support application/javascript for jsonp

廉价感情. 提交于 2019-12-07 18:56:27

Yes, Spring 4.1+ supports JSONP, but it's not a conversion format per se.

MappingJackson2HttpMessageConverter supports "application/json" and "*+json" media types, but does not support "application/javascript". If it did, then you'd expect it to parse javascript code, which is not the case.

Here, we're merely wrapping the output to make it "application/javascript", but really, it's still JSON.

Your current configuration is disabling content negotiation with HTTP Accept headers (why?). In order to support JSONP you only need this in your MVC configuration:

<mvc:annotation-driven/>

And an additional ControllerAdvice like this (see reference documentation):

@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {

    public JsonpAdvice() {
        super("callback");
    }
}

That's it.

Now you'll get:

GET /contextRoot/info/1
// will return what's best depending on the Accept header sent by the client

GET /contextRoot/info/1.xml
// will return XML

GET /contextRoot/info/1.json
// will return JSON

GET /contextRoot/info/1.json?callback=myFunction
// will return JSONP wrapped in a "myFunction" call

In your case, you should:

  1. Remove "application/javascript" from your media types mappings, or for backwards compatibility associate "jsonp" with the "application/json" media type.
  2. Use GET /contextRoot/info/1?formatType=json&param1=callback1

See AbstractJsonpResponseBodyAdvice for more details on the implementation.

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