Spring Boot实现跨域的5种方式

为什么会出现跨域问题什么是跨域非同源限制java后端实现CORS跨域请求的方式返回新的CorsFilter(全局跨域)重写WebMvcConfigurer(全局跨域)使用注解(局部跨域)手动设置响应头(局部跨域)使用自定义filter实现跨域

为什么会出现跨域问题

出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

什么是跨域

当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域

当前页面url被请求页面url是否跨域原因http://www.test.com/http://www.test.com/index.html否同源(协议、域名、端口号相同)http://www.test.com/https:/www.test.com/index.html跨域协议不同 (http/https)http:/www.test.com/http.//www.baidu.com/跨域主域名不同 (test/baidu)http:/lwww.test.com/http.//blogtest.com/跨域子域名不同 (www/bloq)http.//www.test.com.8080/http.//wwwtest.com.7001/跨域端口号不同 (8080/7001)

非同源限制

1.无法读取非同源网页的Cookie、LocalStorage和IndexedDB 2.无法接触非同源网页的DOM 3.无法向非同源地址发送AJAX请求

java后端实现CORS跨域请求的方式

对于CORS的跨域请求,主要有以下几种方式可供选择: 1.返回新的CorsFilter 2.重写WebMvcConfigurer 3.使用注解@CrossOrigin 4.手动设置响应头(HttpServletResponse) 5.自定义web filter实现跨域

注意:

CorsFilter / WebMvcConfigurer / @CrossOrigin 需要SpringMVC 4.2以上版本才支持,对应SpringBoot 1.3版本以上上面前两种方式属于全局CORS配置,后两种属于局部CORS配置。如果使用了局部跨域是会覆盖全局跨域的规则,所以可以通过@CrossOrigin注解来进行细粒度更高的跨域资源控制。其实无论那种方案,最终目的都是修改响应头,响应头中添加浏览器所要求的数据,进而实现跨域。

返回新的CorsFilter(全局跨域)

在任意配置类,返回一个新的 CorsFilter Bean,并添加映射路径和具体的CORS配置路径。

package com.mry.rocketmqdemo.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import org.springframework.web.filter.CorsFilter;

@Configuration

public class GlobalCorsConfig {

@Bean

public CorsFilter corsFilter(){

//1.添加 CORS配置信息

CorsConfiguration config = new CorsConfiguration();

//放行那些原始域

config.addAllowedOrigin("*");

//是否发送 Cookie

config.setAllowCredentials(true);

//放行那些请求方式

config.addAllowedMethod("*");

//放行那些原始请求头部信息

config.addAllowedHeader("*");

//暴露那些头部信息

config.addExposedHeader("*");

//2.添加映射路径

UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();

corsConfigurationSource.registerCorsConfiguration("/**", config);

//3.返回新的CorsFilter

return new CorsFilter(corsConfigurationSource);

}

}

重写WebMvcConfigurer(全局跨域)

package com.mry.rocketmqdemo.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.CorsRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration

public class CorsConfig implements WebMvcConfigurer {

@Override

public void addCorsMappings(CorsRegistry registry){

registry.addMapping("/**")

//是否发送Cookie

.allowCredentials(true)

//放行那些原始域

.allowedOrigins("*")

.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})

.allowedHeaders("*")

.exposedHeaders("*");

}

}

使用注解(局部跨域)

在控制器(类)上使用注解@CrossOrigin,表示该类的所有方法允许跨域。

package com.mry.rocketmqdemo.test;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@CrossOrigin(origins = "*")

public class HelloController {

@RequestMapping("/hello")

public String hello(){

return "hello world";

}

}

在方法上使用注解@CrossOrigin

package com.mry.rocketmqdemo.test;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class HelloController {

@RequestMapping("/hello")

@CrossOrigin(origins = "*")

// @CrossOrigin(value = "http://localhost:8081") //指定具体IP允许跨域

public String hello(){

return "hello world";

}

}

手动设置响应头(局部跨域)

使用HttpServletResponse对象添加响应头(Access-Control-Allow-Origin)来授权原始域,这里Origin的值也可以设置为"*",表示全部放行。

@RequestMapping("/index")

public String index(HttpServletResponse response){

response.addHeader("Access-Control-Allow-Origin", "*");

return "index";

}

使用自定义filter实现跨域

首先编写一个过滤,可以起名字为MyCorsFilter.java

package com.mry.rocketmqdemo.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@Component

public class MyCorsFilter implements Filter {

@Override

public void init(FilterConfig filterConfig) throws ServletException {

}

@Override

public void doFilter(ServletRequest rep, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {

HttpServletResponse response = (HttpServletResponse) res;

response.setHeader("Access-Control-Allow-Origin", "*");

response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

response.setHeader("Access-Control-Max-Age", "3600");

response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");

filterChain.doFilter(rep, res);

}

@Override

public void destroy() {

}

}

在web.xml中配置这个过滤器,使其生效

CorsFilter

com.mesnac.aop.MyCorsFilter

CorsFilter

/*

好文推荐

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: