Tomcat Access-Control-Allow-Origin(同源策略)解決方案

Phoenix Phoenix 2018.3.1 21:05 View(127) Comment (0)

使用tomcat配置cdn服务器时,css文件能正常加载,但是加载字体文件时出现了Access-Control-Allow-Origin错误:

已拦截跨源请求:同源策略禁止读取位于 http://localhost:9999/font-awesome/fonts/fontawesome-webfont.woff2?v=4.5.0 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。(未知)
downloadable font: download failed (font-family: "FontAwesome" style:normal weight:normal stretch:normal src index:1): bad URI or cross-site access not allowed source: http://localhost:9999/font-awesome/fonts/fontawesome-webfont.woff2?v=4.5.0

原因是tomcat禁止了跨域请求。

解决方案

对于标准的war项目包,只需要增加一个filter就能取消Access-Control-Allow-Origin(以下简称CORS)的限制。

首先新建filter类

package com.itxc.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
      FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

然后在web.xml中使用上述filter即可

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.itxc.filter.CORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

本文链接 https://www.mangoxo.com/blog/4z5Kn9Dn 版权所有,转载请保留地址链接,感谢!

Latest Comments :