Spring 跨域問題CORS (Cross Origin Resources Share)
阿新 • • 發佈:2018-11-28
nbsp response ise ride efault -h @override jks ons
4、
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 { }
Spring 跨域問題CORS (Cross Origin Resources Share)