springMVC中fastjson支持jsonp的实现

耗尽温柔 提交于 2019-12-02 14:23:28

1、fastjson自带

如果add多个parameter,会以,做字符串拼接。

... import com.alibaba.fastjson.JSONPObject; ...
@GetMapping("/testjsonp")
@ResponseBody
public Object testjsonp(String callback) {
JSONPObject jsonpObject = new JSONPObject(callback);
jsonpObject.addParameter(Lists.newArrayList("tom"));  //jsonpObject.addParameter("jack");
return jsonpObject;
}

2、jackson自带

// 核心代码块
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
mappingJacksonValue.setJsonpFunction(callback);

3、自定义实现

fastjson支持jsonp的实现:

继承fastjson消息转换器类:com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter

package com.caiya.hongbao.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * fastjson消息转换器
 * Created by caiya on 15/12/23.
 */
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);
            }
    }
}

JSONPObject类:

package com.caiya.hongbao.web;

import java.io.Serializable;

/**
 * Created by caiya on 15/12/23.
 */
public class JSONPObject implements Serializable {

    private static final long serialVersionUID = -7634081032767024781L;

    private String function;

    private Object json;

    public JSONPObject(String function, Object json){
        this.function = function;
        this.json = json;
    }

    public String getFunction() {
        return function;
    }

    public Object getJson() {
        return json;
    }

    public JSONPObject setFunction(String function) {
        this.function = function;
        return this;
    }

    public JSONPObject setJson(Object json) {
        this.json = json;
        return this;
    }

}

spring-web.xml配置:

<bean id="fastJsonHttpMessageConverter"
     class="com.caiya.hongbao.web.MJFastJsonHttpMessageConverter"><!-- com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter -->
   <property name="supportedMediaTypes">
      <list>
         <value>text/html;charset=UTF-8</value>
         <value>application/json;charset=UTF-8</value>
      </list>
   </property>
</bean>
<mvc:annotation-driven>
   <mvc:message-converters>
      <ref bean="fastJsonHttpMessageConverter" />
   </mvc:message-converters>
</mvc:annotation-driven>

controller实例:

/**
 * 个人中心红包列表、红包匹配列表
 * @param status
 * @param channel
 * @param shouldPay
 * @param orderField
 * @param orderType
 * @param page
 * @return
 */
@RequestMapping(value = "/user/hongbao/list", method = RequestMethod.GET)
@ResponseBody
public Object hongbaoList(Integer status, String channel, Long shouldPay, String orderField, String orderType, Page page, String callback) throws SessionException {
    ......
    UserHongbaos userHongbaos = ......
    // 如果callback不为空,那么返回jsonp格式的数据
    if(StringUtils.isNotBlank(callback)){
        return new JSONPObject(callback, userHongbaos);
    }else {
        return userHongbaos;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!