博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot多跨域请求的支持(JSONP)
阅读量:6951 次
发布时间:2019-06-27

本文共 2175 字,大约阅读时间需要 7 分钟。

在我们做项目的过程中,有可能会遇到跨域请求,所以需要我们自己组装支持跨域请求的JSONP数据,而在4.1版本以后的SpringMVC中,为我们提供了一个AbstractJsonpResponseBodyAdvice的类用来支持jsonp的数据(SpringBoot接收解析web请求是依赖于SpringMVC实现的)。下面我们就看一下怎么用AbstractJsonpResponseBodyAdvice来支持跨域请求。

使用AbstractJsonpResponseBodyAdvice来支持跨域请求很简单,只需要继承这个类就可以了。具体代码如下:

package com.zkn.learnspringboot.config;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;/** * Created by wb-zhangkenan on 2016/12/1. */@ControllerAdvice(basePackages = "com.zkn.learnspringboot.web.controller")public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice{    public JsonpAdvice() {        super("callback","jsonp");    }}
下面我们写个类来测试一下:

package com.zkn.learnspringboot.web.controller;import com.zkn.learnspringboot.domain.PersonDomain;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * Created by wb-zhangkenan on 2016/12/1. */@RestController@RequestMapping("/jsonp")public class JsonpTestController {    @Autowired    private PersonDomain personDomain;    @RequestMapping(value = "/testJsonp",produces = MediaType.APPLICATION_JSON_VALUE)    public PersonDomain testJsonp(){        return personDomain;    }}
当我们发送请求为:http://localhost:8003/jsonp/testJsonp的时候,结果如下:

当我们发送的请求为:http://localhost:8003/jsonp/testJsonp?callback=callback的时候,结果如下所示:

看到区别了吗?当我们在请求参数中添加callback参数的时候,返回的数据就是jsonp的,当我们请求参数中不带callback的时候,返回的数据是json的。可以让我们方便的灵活运用。下面再奉上一个jsonp的完整案例。

前台页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>    Title    
后台代码1:

package com.zkn.learnspringmvc.news.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** * Created by zkn on 2016/12/3. */@Controllerpublic class JsonpTestController {    @RequestMapping("testJsonp")    public String testJsonp(){        return "jsonp";    }}
下面我们发送请求如下:http://localhost:8080/LearnSpringMvc/testJsonp

当我们点击测试jsopn请求这个按钮的时候,效果如下:

我们成功的实现了一个跨越的请求。更详细的请求信息如下:

你可能感兴趣的文章
react-navigation升级3.x 问题解决方案
查看>>
redis 学与思系列(4)
查看>>
2019.5.6_普通的一天_用户定义的可调用类型
查看>>
Redis基础、高级特性与性能调优
查看>>
使用Nginx反向代理到go-fastdfs
查看>>
【每日推理2019/06/02】
查看>>
android进程保活实践
查看>>
Activity的四种加载模式之生命周期变化(横竖屏切换)
查看>>
Spark性能优化:优化数据结构
查看>>
又是臭重惹得祸!Office 2016大当机遭微软紧急撤除
查看>>
Flutter 入门之 ListTile 使用指南
查看>>
Android Material Design控件使用(一)——ConstraintLayout 约束布局
查看>>
好程序员Web前端分享程序的三大结构(一)
查看>>
Mac下如何编译 FFmpeg的SO库,为Android使用
查看>>
Spring Cloud构建微服务架构:服务消费(基础)
查看>>
为什么区块链世界既需要计算机科学家也需要经济学家?
查看>>
区块链100讲:10分钟教会你深挖以太坊数据层
查看>>
Sony智慧耳机:不但能轻松叫智能耳机也能与Alexa对话
查看>>
中小企业改造系统适应秒杀的场景
查看>>
Atom 微信小程序文件代码高亮
查看>>