在Tomcat 8.0.30上启用CORS

时间:2016-07-13 14:35:02

标签: java cors tomcat8

感谢任何帮助。

我在新部署的Tomcat 8.0.30上遇到了CORS的问题。我一直收到下面的错误。我使用127.0.0.1作为API服务器地址,192.168.1.100是我的HTTP服务器的地址。

  

否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' _http://192.168.1.100:8999'因此不允许访问。响应的HTTP状态代码为403。

阅读完整的Tomcat文档,在tomcat web.xml下添加了cors过滤器,以及项目web.xml,但这里没有任何魔法发生,仍然得到相同的错误。用init-param尝试了minimal和advanced,同样的错误。

我使用Spring 4作为我的其余api框架。是否需要在项目编码部分进行更多配置?

以下是我目前所做的步骤:

  • 在web.xml下添加cors过滤器,根据文档添加mininal config,不能正​​常工作
  • 在web.xml下添加cors过滤器,完整配置,不能正常工作。
  • 尝试使用来自http://software.dzhuvinov.com/cors-filter.html的cors过滤器,仍然无效

有什么建议吗?

network response

添加web.xml配置 我试图将cors.allowed.origins改为*,到127.0.0.1,192.168.1.100,都没有用, 删除凭据和maxage

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>http://192.168.1.100</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Vishal建议,将tomcat版本从8.0更改为8.5,仍然是同样的问题

 XMLHttpRequest cannot load http://127.0.0.1:8080/leyutech-framework-gurunwanfeng/api/ad/getAdInfoByAdType.html?adType=0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.100:8080' is therefore not allowed access. The response had HTTP status code 403.

2 个答案:

答案 0 :(得分:1)

我遇到过这个问题,我为Jetty Web应用程序开发了一个自定义处理程序。

也许它可以帮到你。

<强> CORSHandler.hava

import java.io.IOException;

import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

public class CORSHandler extends HandlerWrapper {

    public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
    public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
    public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";

    public CORSHandler() {
        super();
    }

    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        // Allow Cross-site HTTP requests (CORS)
        response.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");

        // Accept Content-Type in header
        response.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, "content-type");

        // Accept GET, POST, PUT and DELETE methods
        response.addHeader(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE");

        if (_handler!=null && isStarted())
        {
            _handler.handle(target,baseRequest, request, response);
        }
    }
}

<强> Starter.java

import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.SimpleFormatter;

import org.apache.cxf.transport.servlet.CXFServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.eclipse.jetty.server.handler.HandlerWrapper;

import com.example.config.AppConfig;
import com.example.handlers.CORSHandler;

import com.example.properties.*;

public class Starter {

    public static void main( final String[] args ) throws Exception {

        Server server = new Server( 8080 );

        // Register and map the dispatcher servlet
        final ServletHolder servletHolder = new ServletHolder( new CXFServlet() );

        HandlerWrapper wrapper = new CORSHandler();
        final ServletContextHandler context = new ServletContextHandler();

        context.setContextPath( "/" );
        context.addServlet( servletHolder, "/rest/*" );     
        context.addEventListener( new ContextLoaderListener() );

        context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
        context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() );

        wrapper.setHandler(context);
        server.setHandler(wrapper);

        server.start();
        server.join();  
    }
}

答案 1 :(得分:1)

我已经使用自定义过滤器来完成这个问题,我不知道为什么官方tomcat cors过滤器在我的情况下不起作用,任何人都可以建议这背后的逻辑,我愿意尝试这个。

Original Post from Tobia

从上面的链接修改代码。

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}

当前项目下的web.xml配置

<filter>
    <filter-name>SimpleCORSFilter</filter-name>
    <filter-class>com.example.util.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SimpleCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>