1、Spring给我们提供了三种跨域方法
CorsFilter
过滤器CorsConfiguration
Bean@CrossOrigin
注解
2、CorsFilter 过滤器
CorsFilter代码如下:
package com.xiaobai.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(filterName = "MyFilter") public class MyFilter implements Filter { public void destroy() { } String allowList [] = null; @Override public void init(FilterConfig config) throws ServletException { String origins = config.getInitParameter("allowList"); if(origins != null){ if(origins.equals("*")){ allowList = new String[]{"*"}; }else { allowList = origins.split(","); } } } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { HttpServletResponse response = (HttpServletResponse) servletResponse; HttpServletRequest request = (HttpServletRequest) servletRequest; String origin = request.getHeader("Origin"); if (origin != null && !origin.isEmpty()) { for (String s : allowList) { if (s.equals(origin) || s.equals("*")) { response.setHeader("Access-Control-Allow-Origin", origin); } } } chain.doFilter(request, response); } }
web.xml代码如下:
<filter> <filter-name>MyFilter</filter-name> <filter-class>com.xiaobai.filter.MyFilter</filter-class> <init-param> <param-name>allowList</param-name> <param-value>http://127.0.0.1:8081, http://192.168.2.24:8081</param-value> </init-param> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/aa</url-pattern> </filter-mapping>
3、CorsConfiguration Bean
<mvc:cors>:
<mvc:cors> <mvc:mapping path="/xxx" allowed-origins="http://localhost:7070" allowed-methods="GET, POST" allowed-headers="Accept-Charset, Accept, Content-Type" allow-credentials="true" /> <mvc:mapping path="/yyy/*" allowed-origins="*" allowed-methods="*" allowed-headers="*" /> </mvc:cors>
4、@CrossOrigin
注解
@CrossOrigin 注解本质上也是用来配置 CorsConfiguration。
@CrossOrigin代码如下:
@CrossOrigin public class CORSController { public String cors(@RequestParam(defaultValue = "callback") String callback, HttpServletResponse response) { // 最原始的方式,手动写请求头 response.setHeader("Access-Control-Allow-Origin", "http://192.168.163.1:8081"); return callback + "(‘hello‘)"; } // 将跨域设置在方法上 @RequestMapping("/cors") @CrossOrigin(origins = {"http://localhost:8080", "http://remotehost:82323"}, methods = {RequestMethod.GET, RequestMethod.POST}, allowedHeaders = {"Content-Type", "skfjksdjfk"}, allowCredentials = "true", maxAge = 1898978 ) @RequestMapping("/rrr") public String rrr(@RequestParam(defaultValue = "callback") String callback) { return callback + "(‘rrr‘)"; } }
5、其实也可以采用全注解的方式
结合 @ControllerAdvice 使用,进行全局化:
@Component @ControllerAdvice @CrossOrigin public class CorsAdvice { }
原文地址:https://www.cnblogs.com/Qi1007/p/10030245.html
时间: 2024-11-05 01:06:49