如何在springmvc 中返回jsonp格式

在这里需要使用springmvc4.1或之上的版本。
需要继承MappingJackson2HttpMessageConverter这个类,重写writeInternal方法。
基本步骤:
1写继承MappingJackson2HttpMessageConverter的类

package com.ljlx.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonProcessingException;
//springmvc支持jsonp返回
public class CallbackMappingJackson2HttpMessageConverter extends
        MappingJackson2HttpMessageConverter {
     // 做jsonp的支持的标识,在请求参数中加该参数  
    private String callbackName;  

    @Override  
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {  
        // 从threadLocal中获取当前的Request对象  
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();  
        String callbackParam = request.getParameter(callbackName);  
        if(StringUtils.isEmpty(callbackParam)){  
            // 没有找到callback参数,直接返回json数据  
            super.writeInternal(object, outputMessage);  
        }else{  
            JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());  
            try {  
                String result =callbackParam+"("+super.getObjectMapper().writeValueAsString(object)+");";  
                IOUtils.write(result, outputMessage.getBody(),encoding.getJavaName());  
            }  
            catch (JsonProcessingException ex) {  
                throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);  
            }  
        }  

    }  

    public String getCallbackName() {  
        return callbackName;  
    }  

    public void setCallbackName(String callbackName) {  
        this.callbackName = callbackName;  
    }  
}

2在springmvc.xml文件中添加上自定义消息转换器

    <mvc:annotation-driven >
       
    <mvc:message-converters>  
          
        <bean class="com.ljlx.filter.CallbackMappingJackson2HttpMessageConverter">  
              
            <property name="callbackName" value="callback">property>  
        bean>  
    mvc:message-converters>
    mvc:annotation-driven>

你可能感兴趣的:(java,javaweb,spring)