springboot 跨域示例


springboot 跨域示例

 

跨域:一个应用的前端页面向不同域(协议、域名、端口不全相同)的应用请求数据

说明:跨域请求会自动添加header字段origin表示请求来源,默认情况下跨域请求会被服务端接受并处理,但是浏览器不会接受跨域请求结果,需做配置后才可接收

 

 

**********************

应用 1

 

******************

config 层

 

WebConfig

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
    }
}

 

******************

controller 层

 

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public Map<String,String> hello(HttpServletRequest request){
        Enumeration<String> headers=request.getHeaderNames();
        while (headers.hasMoreElements()){
            String header=headers.nextElement();

            System.out.println(header+" ==> "+request.getHeader(header));
        }

        Map<String,String> map=new HashMap<>();
        map.put("info","hello,瓜田李下");

        return map;
    }
}

 

******************

前端页面

 

index.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/js/jquery-3.5.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btn").click(function () {
                $.get({
                    url: "/hello",
                    success: function (result) {
                        $("#data").html(result.info)
                    }
                })
            });

            $("#btn2").click(function () {
                $.get({
                    url: "http://localhost:8081/hello",
                    success: function (result) {
                        $("#data2").html(result.info)
                    }
                })
            });
        })
    </script>
</head>
<body>
<div th:align="center">
    <button id="btn">获取数据</button>
    <button id="btn2">获取数据2</button><br>
    <span id="data"></span><br>
    <span id="data2"></span>
</div>
</body>
</html>

 

 

 

**********************

应用 2

 

******************

配置文件

 

application.yml

server:
  port: 8081

 

******************

controller 层

 

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public Map<String,String> hello(HttpServletRequest request){
        Enumeration<String> headers=request.getHeaderNames();
        while (headers.hasMoreElements()){
            String header=headers.nextElement();

            System.out.println(header+" ==> "+request.getHeader(header));
        }

        Map<String,String> map=new HashMap<>();
        map.put("info","欢迎你");

        return map;
    }
}

 

 

**********************

使用测试

 

localhost:8080/index

                         

 

点击获取数据

                        

 

 

 

点击获取数据2,无法获取数据

          

 

******************

控制台输出

 

应用 1

2020-07-08 10:16:22.550  INFO 6452 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-08 10:16:22.555  INFO 6452 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
host ==> localhost:8080
connection ==> keep-alive
accept ==> */*
x-requested-with ==> XMLHttpRequest
user-agent ==> Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
referer ==> http://localhost:8080/index
accept-encoding ==> gzip, deflate, br
accept-language ==> zh-CN,zh;q=0.9
cookie ==> isg=BJiYP7OIcordkV4OUKLufIy5acYqgfwLBTEbVdKJqlOGbThXepNTm7QMoaXdorTj

 

应用 2

2020-07-08 10:16:25.402  INFO 1524 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-08 10:16:25.418  INFO 1524 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 16 ms
host ==> localhost:8081
connection ==> keep-alive
accept ==> */*
origin ==> http://localhost:8080
user-agent ==> Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
referer ==> http://localhost:8080/index
accept-encoding ==> gzip, deflate, br
accept-language ==> zh-CN,zh;q=0.9

说明:应用 2多了一个origin请求头,并且不能读取属于应用1 的cookie数据

 

 

 

**********************

跨域配置:应用 2

 

******************

config 层

 

WebConfig

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080");
    }
}

 

 

**********************

使用测试

 

localhost:8080/index

                        

 

点击获取数据

                       

 

点击获取数据2

                      

应用2 配置跨域后,浏览器可正常获取跨域请求返回的数据

 

 

******************

控制台输出

 

应用 1

2020-07-08 10:27:00.531  INFO 22460 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-07-08 10:27:00.532  INFO 22460 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-08 10:27:00.536  INFO 22460 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
host ==> localhost:8080
connection ==> keep-alive
accept ==> */*
x-requested-with ==> XMLHttpRequest
user-agent ==> Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
referer ==> http://localhost:8080/index
accept-encoding ==> gzip, deflate, br
accept-language ==> zh-CN,zh;q=0.9
cookie ==> isg=BJiYP7OIcordkV4OUKLufIy5acYqgfwLBTEbVdKJqlOGbThXepNTm7QMoaXdorTj

 

应用 2

2020-07-08 10:28:15.859  INFO 16648 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-08 10:28:15.868  INFO 16648 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms
host ==> localhost:8081
connection ==> keep-alive
accept ==> */*
origin ==> http://localhost:8080
user-agent ==> Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
referer ==> http://localhost:8080/index
accept-encoding ==> gzip, deflate, br
accept-language ==> zh-CN,zh;q=0.9

此时应用 2仍无法读取属于应用 1的cookie数据,需在请求端发送设置withCredentials、应用 2设置allowCredentials才可读取数据

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值