嵌入式码头CrossDomainFilter无法正常工作

时间:2015-05-01 09:15:15

标签: java jetty cors embedded-jetty

我无法通过处理程序和过滤器的组合找到嵌入式jetty的示例。出于某种原因,我无法确定我没有获得CORS标头。这是我目前的来源:

private static Server setupJetty(Properties prop) {
    Server server = new Server(Integer.parseInt(prop.getProperty("port")));
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath(prop.getProperty("contextpath"));
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    RequestLogHandler requestLogHandler= setupLogging(server, prop.getProperty("logslocn"));
    ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
    jerseyServlet.setInitOrder(0);

    // Tells the Jersey Servlet which REST service/class to load.
    jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "org.example.pss.resources");
    context.addServlet(jerseyServlet, prop.getProperty("servletpath"));

    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(jerseyServlet, "/*");

    FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
    filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");    // allowed origins comma separated
    filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
    filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
    filterHolder.setInitParameter(CrossOriginFilter.PREFLIGHT_MAX_AGE_PARAM, "5184000"); // 2 months
    filterHolder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true");
    filterHolder.setName("cross-origin");
    FilterMapping fm = new FilterMapping();
    fm.setFilterName("cross-origin");
    fm.setPathSpec("*");       
    handler.addFilter(filterHolder,fm);

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{context, handler, contexts, 
            new DefaultHandler(), requestLogHandler});
    server.setHandler(handlers);
    return server;
}

我也尝试过:

    FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
    filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "/*");    // allowed origins comma separated
    filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
    filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
    filterHolder.setInitParameter(CrossOriginFilter.PREFLIGHT_MAX_AGE_PARAM, "5184000"); // 2 months
    filterHolder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true");
    context.addFilter(filterHolder,"/*",EnumSet.allOf(DispatcherType.class));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{context, contexts, 
            new DefaultHandler(), requestLogHandler});
    server.setHandler(handlers);

结果相同,我从未见过跨域标题。我还需要做些什么来使这个过滤器工作?

1 个答案:

答案 0 :(得分:1)

不要直接使用ServletHandler,这是一个内部类。 过滤器始终是ServletContextHandler(或更专业的WebAppContext

的一部分

您的配置在/*上下文路径添加了2个servlet(这是禁忌)

您的配置会在RequestLogHandler之后添加DefaultHandler(这意味着RequestLogHandler永远不会运行)

DefaultHandler应位于主处理程序列表的末尾

DefaultServlet需要存在于ServletContextHandler

您的resourceBase缺少必需的ServletContextHandler(这是指向有效位置的路径或网址,以使ServletContext找到资源的理智位置)

*的路径规范无效。 (请记住,您可以使用前缀/a/b/*,后缀*.foo,完全/a/b/c或默认/

所以,简化......

package org.eclipse.jetty.demo;

import java.util.EnumSet;

import javax.servlet.DispatcherType;

import org.eclipse.jetty.server.AsyncNCSARequestLog;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.servlet.ServletContainer;

public class JerseyWithCors
{
    public static void main(String[] args)
    {
        try
        {
            new JerseyWithCors().exec();
        }
        catch (Throwable t)
        {
            t.printStackTrace(System.err);
        }
    }

    public void exec() throws Exception
    {
        int port = 8080;
        Server server = new Server(port);
        HandlerList handlers = new HandlerList();
        server.setHandler(handlers);

        handlers.addHandler(getAccessLogHandler());
        handlers.addHandler(getMainServletContext());

        // DefaultHandler is always last for the main handler tree
        // It's responsible for Error handling of all prior handlers.
        // It will always respond (if the request reaches this far)
        handlers.addHandler(new DefaultHandler());

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

    public Handler getAccessLogHandler()
    {
        RequestLogHandler logHandler = new RequestLogHandler();
        AsyncNCSARequestLog log = new AsyncNCSARequestLog();
        log.setFilename("logs/access-yyyy_mm_dd.log");
        logHandler.setRequestLog(log);
        return logHandler;
    }

    public Handler getMainServletContext()
    {
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        // always need a resource base
        context.setResourceBase("path/to/webroot");

        ServletHolder jerseyServlet = context.addServlet(ServletContainer.class,"/*");
        jerseyServlet.setInitOrder(0);
        jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES,"org.example.pss.resources");

        FilterHolder filterHolder = context.addFilter(CrossOriginFilter.class,"/*",EnumSet.allOf(DispatcherType.class));
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM,"*");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM,"Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM,"GET,PUT,POST,DELETE,OPTIONS");
        filterHolder.setInitParameter(CrossOriginFilter.PREFLIGHT_MAX_AGE_PARAM,"5184000");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM,"true");

        // DefaultServlet is always last for a ServletContext
        context.addServlet(DefaultServlet.class,"/");

        return context;
    }
}