前后端分离 处理跨域请求 import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.servlet.*;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** *web.xml 配置 CORS com.yls.common.filter.CORSFil
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** *web.xml 配置CORS com.yls.common.filter.CORSFilter cors.allowOrigin * cors.supportedMethods GET, POST, HEAD, PUT, DELETE cors.maxAge 1800 cors.supportedHeaders Accept, Origin, X-Requested-With, Content-Type, Last-Modified cors.supportsCredentials true */ public class CORSFilter implements Filter { /** * 配置 */ private FilterConfig filterConfig; private Logger logger = LoggerFactory.getLogger(CORSFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; logger.info("cros filter init"); /** * 指定了允许访问该资源的外域 URI。对于不需要携带身份凭证的请求,服务器可以指定该字段的值为通配符,表示允许来自所有域的请求。 */ logger.info("Access-Control-Allow-Origin: " + filterConfig.getInitParameter("cors.allowOrigin")); /** * 首部字段用于预检请求的响应。其指明了实际请求所允许使用的 HTTP 方法。 */ logger.info("Access-Control-Allow-Methods: " + filterConfig.getInitParameter("cors.supportedMethods")); /** * 请求的结果能够被缓存多久 */ logger.info("Access-Control-Max-Age: " + filterConfig.getInitParameter("cors.maxAge")); /** * 在跨域访问时,XMLHttpRequest对象的getResponseHeader()方法只能拿到一些最基本的响应头, * Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma, * 如果要访问其他头,则需要服务器设置本响应头。Access-Control-Expose-Headers 头让服务器把允许浏览器访问的头放入白名单 */ logger.info("Access-Control-Allow-Headers: " + filterConfig.getInitParameter("cors.supportedHeaders")); /** * 头指定了当浏览器的credentials设置为true时是否允许浏览器读取response的内容。 * 当用在对preflight预检测请求的响应中时,它指定了实际的请求是否可以使用credentials。 * 请注意:简单 GET 请求不会被预检;如果对此类请求的响应中不包含该字段,这个响应将被忽略掉, * 并且浏览器也不会将相应内容返回给网页。 */ logger.info("Access-Control-Allow-Credentials: " + filterConfig.getInitParameter("cors.supportsCredentials")); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Access-Control-Allow-Origin", filterConfig.getInitParameter("cors.allowOrigin")); httpResponse.setHeader("Access-Control-Allow-Methods", filterConfig.getInitParameter("cors.supportedMethods")); httpResponse.setHeader("Access-Control-Max-Age", filterConfig.getInitParameter("cors.maxAge")); httpResponse.setHeader("Access-Control-Allow-Headers", filterConfig.getInitParameter("cors.supportedHeaders")); httpResponse.setHeader("Access-Control-Allow-Credentials", filterConfig.getInitParameter("cors.supportsCredentials")); chain.doFilter(request, httpResponse); } @Override public void destroy() { logger.info("cros filter destroy"); } } CORS /api/*