当前位置: 代码迷 >> 综合 >> SpringMVC CORS 解决跨域问题
  详细解决方案

SpringMVC CORS 解决跨域问题

热度:94   发布时间:2023-09-29 05:11:42.0

1、补充知识

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。

所谓同源是指,域名,协议,端口相同。

 目前主流的跨域访问技术有JSONP和CORS,JSONP的优势在于能够支持较老版本的浏览器,弱势在于只能处理GET的请求,而CORS的优势在于能处理所有类型的请求,但弱势在于不能处理IE8以下版本的请求

2、跨域解决方法

(1)web.xml加入过滤器配置

<filter><filter-name>CORS</filter-name><filter-class>com.fh.filter.CrossDomainFilter</filter-class><init-param><param-name>cors.allowOrigin</param-name><param-value>*</param-value></init-param><init-param><param-name>cors.supportedMethods</param-name><param-value>GET, POST, HEAD, PUT, DELETE</param-value></init-param><init-param><param-name>cors.supportedHeaders</param-name><param-value>Accept, Origin, XRequestedWith, Content-Type, LastModified</param-value></init-param><init-param><param-name>cors.exposedHeaders</param-name><param-value>SetCookie</param-value></init-param><init-param><param-name>cors.supportsCredentials</param-name><param-value>true</param-value></init-param>
</filter>
<filter-mapping><filter-name>CORS</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>

(2)过滤器配置类

package com.fh.filter;import com.thetransactioncompany.cors.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;public class CrossDomainFilter extends CORSFilter {private final List<String> allowedOrigins = Arrays.asList("http://localhost:8088","http://www.wedive.com:9000");private CORSConfiguration config;private CORSRequestHandler handler;public CrossDomainFilter() {}public CrossDomainFilter(CORSConfiguration config) {this.setConfiguration(config);}@Override
    public void setConfiguration(CORSConfiguration config) {this.config = config;this.handler = new CORSRequestHandler(config);}@Override
    public CORSConfiguration getConfiguration() {return this.config;}@Override
    public void init(FilterConfig filterConfig) throws ServletException {CORSConfigurationLoader configLoader = new CORSConfigurationLoader(filterConfig);try {this.setConfiguration(configLoader.load());} catch (CORSConfigurationException var4) {throw new ServletException(var4.getMessage(), var4);}}private void printMessage(CORSException corsException, HttpServletResponse response) throws IOException, ServletException {response.setStatus(corsException.getHTTPStatusCode());response.resetBuffer();response.setContentType("text/plain");PrintWriter out = response.getWriter();out.println("Cross-Origin Resource Sharing (CORS) Filter: " + corsException.getMessage());}private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {CORSRequestType type = CORSRequestType.detect(request);if (this.config.tagRequests) {RequestTagger.tag(request, type);}try {if (type.equals(CORSRequestType.ACTUAL)) {this.handler.handleActualRequest(request, response);CORSResponseWrapper responseWrapper = new CORSResponseWrapper(response);chain.doFilter(request, responseWrapper);} else if (type.equals(CORSRequestType.PREFLIGHT)) {this.handler.handlePreflightRequest(request, response);} else if (this.config.allowGenericHttpRequests) {chain.doFilter(request, response);} else {this.printMessage(CORSException.GENERIC_HTTP_NOT_ALLOWED, response);}} catch (CORSException var6) {this.printMessage(var6, response);}}@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {this.doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain);} else {throw new ServletException("Cannot filter non-HTTP requests/responses");}}@Override
    public void destroy() {}
}

  相关解决方案