zoukankan      html  css  js  c++  java
  • SpringMVC使用fastjson自定义Converter支持返回jsonp格式(转)

    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;
        }
  • 相关阅读:
    【线段树 树链剖分 差分 经典技巧】loj#3046. 「ZJOI2019」语言【未完】
    【图论 思维】cf715B. Complete The Graph加强
    【A* 网络流】codechef Chef and Cut
    【主席树上二分】bzoj5361: [Lydsy1805月赛]对称数
    蓝书例题之UVa 10253 Series-Parallel Networks
    HAOI2019+十二省联考 游记
    Beyas定理
    CF739E Gosha is hunting DP+wqs二分
    wqs二分
    线性规划之单纯形算法
  • 原文地址:https://www.cnblogs.com/keyi/p/7649759.html
Copyright © 2011-2022 走看看