zoukankan      html  css  js  c++  java
  • springmvc 对 jsonp 的支持

    在与前端开发人员合作过程中,经常遇到跨域名访问的问题,通常我们是通过jsonp调用方式来解决。jsop百科:http://baike.baidu.com/link?url=JKlwoETqx2uuKeoRwlk_y6HZ9FZxXTARLwm7QFOmuqex5p6-Ch5GQpSM5juf614F8hYaP2N3wDkU26slwvtnOa

    如:请求 http://xxxx?&callback=exec , 那么返回的jsonp格式为 exec({"code":0, "message":"success"}); 。 其实对于格式的重新封装并不复杂,但是对于某个请求既要支持json返回也要支持jsop返回怎么做,那我们就得做个判断, if(request.getParameter("callback")  != null),  如果存在就返回jsonp, 不存在就返回json。 

    在使用springmvc的场景下,如何利用springmvc来返回jsonp格式,有很多方式可以实现。 这里介绍一种比较简单但比较通用的处理方式。前提是你使用的springmvc是4.1版本及以上。主要是要继承类AbstractJsonpResponseBodyAdvice, 并加入@ControllerAdvice 这个注解,basePackages 标识要被处理的controller。

    实现代码如下:

     1 @ControllerAdvice(basePackages = "xxx.controller")
     2 public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
     3 
     4     private final String[] jsonpQueryParamNames;
     5 
     6     public JsonpAdvice() {
     7         super("callback", "jsonp");
     8         this.jsonpQueryParamNames = new String[]{"callback"};
     9     }
    10 
    11     @Override
    12     protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
    13                                            MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
    14 
    15         HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    16      
    17      //如果不存在callback这个请求参数,直接返回,不需要处理为jsonp
    18         if (ObjectUtils.isEmpty(servletRequest.getParameter("callback"))) {
    19             return;
    20         }
    21      //按设定的请求参数(JsonAdvice构造方法中的this.jsonpQueryParamNames = new String[]{"callback"};),处理返回结果为jsonp格式
    22         for (String name : this.jsonpQueryParamNames) {
    23             String value = servletRequest.getParameter(name);
    24             if (value != null) {
    25                 MediaType contentTypeToUse = getContentType(contentType, request, response);
    26                 response.getHeaders().setContentType(contentTypeToUse);
    27                 bodyContainer.setJsonpFunction(value);
    28                 return;
    29             }
    30         }
    31     }
    32 }
  • 相关阅读:
    我在D2讲演的视频,已经可以下载了~
    走出海量数据及访问量压力困境
    博客作者应该学习的15个国外博客
    如何将jsp动态网页转换成静态页面
    新一代网络模式Web 2.0火爆发展
    数据库设计中的14个关键技巧
    如何进行RSS推广
    运用RUP 4+1视图方法进行软件架构设计
    02java关键词变量类型
    03java运算符函数
  • 原文地址:https://www.cnblogs.com/blacksonny/p/5846411.html
Copyright © 2011-2022 走看看