【转】两步使 Spring MVC 4.0 支持 JSONP
Step 1 : 添加JSONP转换器
public class JsonpHttpMessageConverter extends MappingJackson2HttpMessageConverter { @Override protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType()); JsonGenerator jsonGenerator = this.getObjectMapper().getFactory().createGenerator(outputMessage.getBody(), encoding); try { //ConfigContainer.JSONP_CALLBACK 为回调名称,如"callback" jsonGenerator.writeRaw(ConfigContainer.JSONP_CALLBACK); jsonGenerator.writeRaw('('); this.getObjectMapper().writeValue(jsonGenerator, object); jsonGenerator.writeRaw(");"); jsonGenerator.flush(); } catch (JsonProcessingException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } } }
step 2 : 添加配置
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="...JsonpHttpMessageConverter" p:supportedMediaTypes="application/jsonp"/> </mvc:message-converters> </mvc:annotation-driven>
ok!
test:
$.ajax({ type: <your type>, url: <your url>, dataType: 'jsonp', jsonpCallback: 'JsonpCallback', //这个值要与第一步的ConfigContainer.JSONP_CALLBACK同名 contentType: 'application/jsonp;charset=UTF-8', }).done(function (result) { //TODO }).fail(function (result, textStatus, info) { //TODO }); }
相关推荐
fengchao000 2020-06-17
adonislu 2020-05-16
zmosquito 2020-05-10
adonislu 2020-05-10
somebodyoneday 2020-04-22
fengchao000 2020-04-22
fengchao000 2020-04-11
Richardxx 2020-03-07
somebodyoneday 2020-03-06
fengchao000 2020-03-05
somebodyoneday 2020-02-16
xiaouncle 2020-02-13
baijinswpu 2020-01-29
fengchao000 2020-01-10
fengchao000 2019-12-25
newthon 2019-12-23
somebodyoneday 2013-07-11