SpringBoot---CROS 跨域请求

一、Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等 CORS 与 JSONP 相比  
1、 JSONP 只能实现 GET 请求,而 CORS 支持所有类型的 HTTP 请求。 
2、 使用 CORS,开发者可以使用普通的 XMLHttpRequest 发起请求和获得数据,比起 JSONP 有更好的
错误处理。 
3、 JSONP 主要被老的浏览器支持,它们往往不支持 CORS,而绝大多数现代浏览器都已经支持了 CORS 
 
     浏览器支持情况 
     Chrome 3+ 
     Firefox 3.5+ 
     Opera 12+ 
     Safari 4+ 
     Internet Explorer 8+ 
 
二、在 spring MVC 中可以配置全局的规则,也可以使用@CrossOrigin 注解进行细粒度的配置。 

全局配置: 
@Configuration 
public class CustomCorsConfiguration { 
  
 @Bean 
 public WebMvcConfigurer corsConfigurer() { 
  return new WebMvcConfigurerAdapter() { 
   @Override 
   public void addCorsMappings(CorsRegistry registry) { 
    registry.addMapping("/api/**").allowedOrigins("http://localhost:8080"); 
   } 
  }; 
 } 

 
或者是 
/** 
 * 全局设置 
 *  
 * @author wujing 
 */ 
@Configuration 
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter { 
  

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

 
定义方法: 
/** 
 * @author wujing 
 */ 
@RestController 
@RequestMapping("/api") 
public class ApiController { 
 
 @RequestMapping(value = "/get") 
 public HashMap<String, Object> get(@RequestParam String name) { 
  HashMap<String, Object> map = new HashMap<String, Object>(); 
  map.put("title", "hello world"); 
  map.put("name", name); 
  return map; 
 } 

 
测试 js: 
$.ajax({ 
           url: "http://localhost:8081/api/get", 
              type: "POST", 
              data: { 
                  name: "测试" 
              }, 
              success: function(data, status, xhr) { 
               console.log(data); 
               alert(data.name); 
              } 
             }); 
 
细粒度配置 
 
/** 
 * @author wujing 
 */ 
@RestController 
@RequestMapping(value = "/api", method = RequestMethod.POST) 
public class ApiController { 
 @CrossOrigin(origins = "http://localhost:8888") 
 @RequestMapping(value = "/get") 
 public HashMap<String, Object> get(@RequestParam String name) { 
  HashMap<String, Object> map = new HashMap<String, Object>(); 
  map.put("title", "hello world"); 
  map.put("name", name); 
  return map; 
 } 

使用两个SpringBoot项目完成完成跨越请求。在SpringBoot-demo-10-1项目中完成向http://localhost:8888/api/get(SpringBoot-demo-11-1)发送请求

   index.ftl代码如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
    <link href="/css/index.css"/>
<#--<script type="text/javascript" src="/js/jquery-1.8.3.min.js"></script>-->
    <script type="text/javascript" src="/webjars/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<center>
    <h1>首页</h1>
    <img src="/images/logo.png" />
    <h1 id="title">${title}</h1>
</center>

<script>
    $(function(){
        $('#title').click(function(){
            $.ajax({
                url: "http://localhost:8080/api/get",
                type: "POST",
                data: {
                    name: "测试"
                },
                success: function(data, status, xhr) {
                    console.log(data);
                    alert(data.name);
                }
            });
        });
    })
</script>
</body>
</html>

SpringBoot-demo-11-1 ApiControlle如下:

package com.nyist.demo.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;

     /**
      * @author wujing
      */
     @RestController
     @RequestMapping("/api")
     public class ApiController {

      @RequestMapping(value = "/get")
      public HashMap<String, Object> get(@RequestParam String name) {
       HashMap<String, Object> map = new HashMap<String, Object>();
       map.put("title", "hello world");
       map.put("name", name);
       System.out.println("******************************");
       System.out.println("*                            *");
       System.out.println("******************************");
       return map;
      }
} 

跨域请求配置java代码:

package com.nyist.demo.utils.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CustomCorsConfiguration { 
  
     @Bean
     public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurerAdapter() {
       @Override
       public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**").allowedOrigins("http://localhost:8888");
       }
      };
     }
}

ps:SpringBoot-demo-10-1 启动的端口为8888 SpringBoot-demo-11-1启动的端口为8080,我们访问http://localhost:8888/web/index (即可fang访问到/templates/index.ftl) 结果如下:

  在SpringBoot-demo-11-1控制台下看到的结果如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值