springboot 的jsonp跨域请求统一配置
1 可以继承AbstractHttpMessageConverter类
在这里插入代码片
@Component
public class CustomHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
//请求是 GET + Accept: application/x-java-serialization,
//返回的是 Content-Type: application/x-java-serialization;charset=UTF-8 的Java序列化格式的报文
public CustomHttpMessageConverter() {
// 构造方法中指明请求(req)和响应(resp)的类型,指明这个类型才会使用这个converter
super(StandardCharsets.UTF_8, MediaType.ALL);//指定所有的类型
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
}
// 读数据 读取request的body
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return JSONObject.parseObject(StreamUtils.copyToString(inputMessage.getBody(), StandardCharsets.UTF_8));
}
// 做jsonp的支持的标识
private String callback; // 值为callback
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
//对象与json的转换
public static final ObjectMapper mapper = new ObjectMapper();
// Object 是返回的信息 重新 写出数据 把数据写到response的body中
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
System.out.println("===========正在加载自定义消息转换器configureMessageConverters======");
// 获取请求参数值
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String callbackParam = request.getParameter(callback);
System.out.println("===========请求参数值为callback==========" + callbackParam);
System.out.println("===========正在写出数据==========" + o);
// 判断值是否为空
if (StringUtils.isEmpty(callbackParam)) { // 不是跨域请求
byte[] b = JSONObject.toJSONBytes(o);
outputMessage.getBody().write(b);// 返回接json数据
} else {
// 是跨域请求
try {
// 2 将对象转为json字符串 和callback参数拼接 进行包裹 返回string
//String result = callbackParam+"("+mapper.writeValueAsString(result)+");";
String result = callbackParam + "(" + JSONObject.toJSONString(o) + ");";
byte[] res = result.getBytes();
// 输出结果
outputMessage.getBody().write(res);
} catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}
}
}
}
2 在标注@Configuration的注解类中添加一个Bean会自动注入
在这里插入代码片
@Bean
public CustomHttpMessageConverter cus(){
CustomHttpMessageConverter c = new CustomHttpMessageConverter();
c.setCallback("callback");//设置请求参数值为callback
return c;
}
也可以extends WebMvcConfigurerAdapter 重写 extendMessageConverters方法
在这里插入代码片
@Configuration
public class SpringMvcIntercepter extends WebMvcConfigurerAdapter{
//注意@Component注解别忘了
@Resource
private CustomHttpMessageConverter cus;
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
cus.setCallback("callback");
// 加入自定义的
converters.add(cus);
}
}
3 也可以直接在CustomHttpMessageConverter 这个类的上面直接添@Component 注解 就会直接生效
总结及注意问题:
1继承AbstractHttpMessageConverter可以实现没有问题
2继承MappingJackson2HttpMessageConverter就没法实现,无法使自定义的消息转换器生效,不知原因