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 }
  • 相关阅读:
    P3146 [USACO16OPEN]248
    P2590 [ZJOI2008]树的统计
    P3379 【模板】最近公共祖先(LCA)
    P2253 好一个一中腰鼓!
    数组中出现次数超过一半的数字
    字符串的排列
    二叉搜索树与双向链表
    二叉搜索树的后序遍历序列
    从上往下打印二叉树
    顺时针打印矩阵
  • 原文地址:https://www.cnblogs.com/blacksonny/p/5846411.html
Copyright © 2011-2022 走看看