Created
July 12, 2013 03:30
-
-
Save arganzheng/5981192 to your computer and use it in GitHub Desktop.
支持JSONP返回格式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(");"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
有时候根本没有走到json的converter,在spring-controller.xml中配置一下这个: