Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arganzheng/5981192 to your computer and use it in GitHub Desktop.
Save arganzheng/5981192 to your computer and use it in GitHub Desktop.
支持JSONP返回格式
package me.arganzheng.study;
import java.io.IOException;
import java.io.PrintStream;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 支持JSONP返回格式
*
* @author arganzheng
*/
public class MappingJsonpHttpMessageConverter extends MappingJacksonHttpMessageConverter {
public MappingJsonpHttpMessageConverter(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL));
setObjectMapper(objectMapper);
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
String jsonpCallback = null;
RequestAttributes reqAttrs = RequestContextHolder.currentRequestAttributes();
if (reqAttrs instanceof ServletRequestAttributes) {
jsonpCallback = ((ServletRequestAttributes) reqAttrs).getRequest().getParameter("callback");
}
if (jsonpCallback != null) {
new PrintStream(outputMessage.getBody()).print(jsonpCallback + "(");
}
super.writeInternal(o, outputMessage);
if (jsonpCallback != null) {
new PrintStream(outputMessage.getBody()).println(");");
}
}
}
@arganzheng
Copy link
Author

有时候根本没有走到json的converter,在spring-controller.xml中配置一下这个:

<bean id="contentNegotiationManager"
    class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="false" />
    <property name="ignoreAcceptHeader" value="false" />
    <property name="mediaTypes">
        <value>
            html=text/html
            json=application/json
            *=*/*
        </value>
    </property>
</bean>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment