web之家  
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;
    }
posted on 2017-10-11 11:34  路修远而求索  阅读(3430)  评论(0编辑  收藏  举报