网上充斥着 类似(下面) 的无脑回答
@ControllerAdvice(basePackages = "com.controller")
public class Jsonp extends AbstractJsonpResponseBodyAdvice {
public Jsonp() {
//构造函数
super("callback","jsonp");
}
}
然而 AbstractJsonpResponseBodyAdvice
这个类 spring 官方找废弃了。
(可能考虑到 jsonp 这个技术 有点 low ,迟早要淘汰把)
<mark>但是,奈何不了我们可爱的前端喜欢用啊。</mark>
功能还是要实现的。(下面)
就是用 RequestContextHolder
这个 ThreadLocal
获得当前线程的 request
判断一下,有需要就做个 字符串拼接
package cn.test.config;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.fasterxml.jackson.core.JsonGenerator;
@Configuration
public class JsonpConfig {
@Bean
public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
return new MappingJackson2HttpMessageConverter() {
// 做jsonp的支持的标识,在请求参数中加该参数
private final static String CALLBACK = "callback";
// 获取callback参数
private String parseCallbackParam() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes()).getRequest();
return request.getParameter(CALLBACK);
}
@Override
protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
String callback = parseCallbackParam();
if (!StringUtils.isEmpty(callback))
generator.writeRaw(callback + "(");
}
@Override
protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
String callback = parseCallbackParam();
if (!StringUtils.isEmpty(callback))
generator.writeRaw(")");
}
};
}
}