import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.cim.domain.dto.JSONPObject; import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException; import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset; /**
* @author 郑明亮
* @time 2017年6月1日 上午11:51:57
* @description <p>自定义转换器,拼接jsonp格式数据 </p>
* @modifyBy
* @modifyTime
* @modifyDescription<p> </p>
*/
public class MJFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
public static final Charset UTF8 = Charset.forName("UTF-8");
private Charset charset;
private SerializerFeature[] features; public MJFastJsonHttpMessageConverter() {
super();
this.charset = UTF8;
this.features = new SerializerFeature[0];
} @Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
// obj就是controller中注解为@ResponseBody的方法返回值对象
if(obj instanceof JSONPObject){
JSONPObject jsonpObject = (JSONPObject)obj;
OutputStream out = outputMessage.getBody();
String text = JSON.toJSONString(jsonpObject.getJson(), this.features);
String jsonpText = new StringBuilder(jsonpObject.getFunction()).append("(").append(text).append(")").toString();
byte[] bytes = jsonpText.getBytes(this.charset);
out.write(bytes);
}else{
super.writeInternal(obj, outputMessage);
}
}
}

修改spring-mvc.xml

将spring-mvc.xml中原来fastjson的转换器引用类改成自定义的Converter类

<!-- 避免IE执行AJAX时,返回JSON出现下载文件 --><!-- com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!--改成自己的自定义转换类 -->
<bean id="jsonConverter" class="com.zml.common.util.MJFastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="features">
<array>
<value>WriteMapNullValue</value>
<value>WriteNullStringAsEmpty</value>
<value>QuoteFieldNames</value>
<value>DisableCircularReferenceDetect</value>
</array>
</property>
</bean> </mvc:message-converters>
</mvc:annotation-driven>
Controller 方法实例

注意返回类型写成Object,以及添加入参callback,根据callback是否有值来判断返回格式为json还是jsonp

/**
* @author 郑明亮
* @time 2017年6月1日 下午6:48:40
* @description <p> 根据条件查询mongoDB监控日志信息</p>
* @modifyBy
* @modifyTime
* @modifyDescription<p> </p>
* @param vo 日志查询条件扩展类
* @param typeList 监控日志类型,增 1 删2 改3 查4
* @param callback jsonp回调方法名称
* @return
*/
@RequestMapping("/queryMonitorLogs")
@ResponseBody
public Object queryMonitorLogs(MonitorLogVO vo,String collectionName,Integer [] typeList,String callback){
log.info("---入参:---"+vo);
if (typeList != null && typeList.length > 0) {
vo.setTypeList(Arrays.asList(typeList));
}
Tidings<Page<MonitorLog>> tidings = new Tidings<>();
String msg = "查询异常";
String status = ERROR;
Page<MonitorLog> page = null;
try {
page = monitorLogService.findByVO(vo,collectionName);
if (page.getTotalCount() == 0) {
msg = "查询成功,但未查询到数据";
status = SUCCESS_BUT_NULL;
}else {
msg = "查询成功";
status = SUCCESS;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} tidings.setMsg(msg);
tidings.setStatus(status);
tidings.setData(page);
log.info("---出参:---"+tidings);
if (callback != null) {
return new JSONPObject(callback,tidings);
} return tidings;
}

SpringMVC使用fastjson自定义Converter支持返回jsonp格式(转)的更多相关文章

  1. spring mvc fastJson 自定义类型转换(返回数据) 实现对ObjectId类型转换

    json用的alibaba fastJson ValueFilter filter = new ValueFilter() { @Override public Object process(Obje ...

  2. 自定义统一api返回json格式(app后台框架搭建三)

    在统一json自定义格式的方式有多种:1,直接重写@reposeBody的实现,2,自定义一个注解,自己去解析对象成为json字符串进行返回 第一种方式,我就不推荐,想弄得的话,可以自己去研究一下源码 ...

  3. SpringBoot22 Ajax跨域、SpringBoot返回JSONP、CSRF、CORS

    1 扫盲知识 1.1 Ajax为什么存在跨域问题 因为浏览器处于安全性的考虑不允许JS执行跨域请求. 1.2 浏览器为什么要限制JS的跨域访问 如果浏览器允许JS的跨域请求就很容易造成 CSRF (C ...

  4. SpringMVC中fastjson支持jsonp的实现

    前边一篇文章主要说了下前端处理jsonp的方式,这篇主要介绍了后台接收和响应jsonp的一种方式 继承fastjson消息转换器类:com.alibaba.fastjson.support.sprin ...

  5. SpringBoot RestController 同时支持返回xml和json格式数据

    @RestController 默认支持返回json格式数据,即使不做任何配置也能返回json数据 当接口需要支持xml或json两种格式数据时应该怎么做呢? 只要引入 Jackson xml的 ma ...

  6. Asp.net mvc返回Xml结果,扩展Controller实现XmlResult以返回XML格式数据

    我们都知道Asp.net MVC自带的Action可以有多种类型,比如ActionResult,ContentResult,JsonResult……,但是很遗憾没有支持直接返回XML的XmlResul ...

  7. springmvc 自定义view支持json和jsonp格式数据返回

    1.如果controlloer上用@ResponseBody注解,则用<mvc:message-converter>里面配置的json解析器进行解析 <mvc:annotation- ...

  8. SpringMVC返回Json,自定义Json中Date类型格式

    http://www.cnblogs.com/jsczljh/p/3654636.html —————————————————————————————————————————————————————— ...

  9. SpringMVC通过实体类返回json格式的字符串,并在前端显示

    一.除了搭建springmvc框架需要的jar包外,还需要这两个jar包 jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar 二.web,. ...

随机推荐

  1. 九度OJ 1056:最大公约数 (GCD)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:6278 解决:4075 题目描述: 输入两个正整数,求其最大公约数. 输入: 测试数据有多组,每组输入两个正整数. 输出: 对于每组输入,请 ...

  2. 扩容数据盘_Linux

    扩容数据盘_Linux_扩容云盘_云盘_用户指南_云服务器 ECS-阿里云 https://help.aliyun.com/document_detail/25452.html 磁盘扩容付费后: 在控 ...

  3. 【题解】P3129高低卡(白金)High Card Low Card

    [题解][P3129 USACO15DEC]高低卡(白金)High Card Low Card (Platinum) 考虑贪心. 枚举在第几局改变规则,在改变规则之前,尽量出比它大的最小的牌,在改变规 ...

  4. Machine Learning in Action(4) Logistic Regression

    从这节算是开始进入“正规”的机器学习了吧,之所以“正规”因为它开始要建立价值函数(cost function),接着优化价值函数求出权重,然后测试验证.这整套的流程是机器学习必经环节.今天要学习的话题 ...

  5. PAT 乙级 1085. PAT单位排行 (25) 【结构体排序】

    题目链接 https://www.patest.cn/contests/pat-b-practise/1085 思路 结构体排序 要注意几个点 它的加权总分 是 取其整数部分 也就是 要 向下取整 然 ...

  6. js作用域总结

    一.在ES5中,js 的作用域 js作用域,只有全局作用域与函数作用域,没有块级作用域. 1.全局作用域 var a = 10; function aaa() {alert(a) } function ...

  7. 笔记 jsp/ajax/js/jquery/html5/css+div->table

    1. jsp 1).jsp(39,33)   equal symbol expected: 这个异常是说第39行有 " '( 冒号单引号)问题 2)${map[key]}  map和key换 ...

  8. 分布式任务调度平台XXL-Job搭建

    下载: https://github.com/xuxueli/xxl-job 下载 然后倒入到自己的工程里面 引入后: 导入数据:跑一边 导入: 修改: Window -->show view- ...

  9. plugin scala is incompatible with current installation

    源文链接:http://stackoverflow.com/questions/31927516/plugin-scala-is-incompatible-with-this-installation ...

  10. ubuntu gitlab服务器搭建

    gitlab服务器搭建 1.安装依赖包 sudo apt-get install curl openssh-server ca-certificates postfix 执行完成后,出现邮件配置,选择 ...