SpringMVC 自动识别JSON与JSONP请求,返回基于FastJSON
2016-03-18 13:20
441 查看
package com.loowj.web.springmvc; import com.alibaba.fastjson.JSON; 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 org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * Created by luoweijun on 2016/3/18. * concat loowj@loowj.com */ public class FastJsonJsonpHttpMessageConverter extends FastJsonHttpMessageConverter { protected String[] jsonpParameterNames = new String[]{"callback","jsonp"}; @Override protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String text = JSON.toJSONString(obj, getFeatures()); String callback = null; for (int i = 0; i< jsonpParameterNames.length; i++){ callback = request.getParameter(jsonpParameterNames[i]); if(callback != null) { break; } } if(StringUtils.isNotBlank(callback)){ text = new StringBuilder(callback).append("(").append(text).append(")").toString(); } outputMessage.getBody().write(text.getBytes(getCharset())); } public void setJsonpParameterNames(String[] jsonpParameterNames) { this.jsonpParameterNames = jsonpParameterNames; } }
<!-- 启用默认配置 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 配置Fastjson支持 --> <bean class="com.loowj.web.springmvc.FastJsonJsonpHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
注意:
方法上必须添加:@ResponseBody
$.ajax({ type:'POST', dataType: "jsonp", jsonp: 'jsonp', success:function(){ } });
相关文章推荐
- JAVA基础(21) java代码替换指定url里的参数值
- 201. Bitwise AND of Numbers Range | Java最短代码实现
- 第二周JAVA学习笔记(二)
- Spring 使用注解方式进行事务管理
- java -Xms -Xmx -XX:PermSize -XX:MaxPermSize
- 82. Remove Duplicates from Sorted List II | Java最短代码实现
- Generics
- 200. Number of Islands | Java最短代码实现
- spring后台返回json数据 页面406错误 Not Acceptable解决
- Spring AOP面向切面编程及两种动态代理
- MyEclipse里面跑项目的时候,直接来了个这样的错误导致不能正常运行。MyEclipse也直接卡死不动了。
- Java获取随机数的方法
- java入门基础笔记第四天
- 编程从Java开始
- java复习总结5
- [转]Struts2理解--动态方法和method属性及通配符_默认Action
- 调试JDK源码-ConcurrentHashMap实现原理
- Java中构造函数重载和方法重载
- Java线程:新特征-有返回值的线程
- java零基础入门笔记第三天