【转】两步使 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
    });
}

原文地址:http://my.oschina.net/gudaoxuri/blog/340936