26

我将码头嵌入到我的应用程序中,并试图弄清楚如何添加 servlet 过滤器(用于 cookie 处理)。wiki 和 javadoc 并没有说得很清楚,我错过了什么:

Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
FilterHolder f = new FilterHolder(new AuthorisationFilter());
context.addFilter(... f ...); // ?????
context.addServlet(new ServletHolder(new TestServlet()), "/");

我在这方面找到的唯一信息是一个论坛帖子,建议需要改进这方面的文档。

4

4 回答 4

27

我遇到了同样的问题,但我认为 Καrτhικ 的答案太复杂了。我发现了这个简单的方法:

Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/");
context.addFilter(AppFilter.class, "/*", EnumSet.of(DispatcherType.INCLUDE,DispatcherType.REQUEST));

server.setHandler(context);
server.start();
server.join();

我的码头版本是8.1.14.v20131031.

于 2014-05-23T08:31:30.207 回答
26

更新:对于 Jetty 版本 9.2.2:

    Server server = new Server();

    // Note: if you don't want control over type of connector, etc. you can simply 
    // call new Server(<port>);
    ServerConnector connector = new ServerConnector(server);
    connector.setHost("0.0.0.0");
    connector.setPort(8085);
    // Setting the name allows you to serve different app contexts from different connectors.
    connector.setName("main");
    server.addConnector(connector);

    WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    // For development within an IDE like Eclipse, you can directly point to the web.xml
    context.setWar("src/main/webapp");
    context.addFilter(MyFilter.class, "/", 1);

    HandlerCollection collection = new HandlerCollection();
    RequestLogHandler rlh = new RequestLogHandler();
    // Slf4j - who uses anything else?
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(false);
    rlh.setRequestLog(requestLog);
    collection.setHandlers(new Handler[] { context, rlh });
    server.setHandler(collection);

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        // Google guava way
        throw Throwables.propagate(e);
    }

原始答案===

如果您不想使用 web.xml,请使用以下命令:

SocketConnector socketConnector = new SocketConnector();
socketConnector.setPort(7000); // Change to port you want
Server server.setConnectors(new Connector[] { socketConnector });

WebAppContext webapp = new WebAppContext();

webapp.setContextPath("/"); // For root
webapp.setWar("/"); // Appropriate file system path.

// Now you can use the various webapp.addFilter() methods
webapp.addFilter(MyFilter.class, "/test", 1); // Will serve request to /test.
// There are 3 different addFilter() variants.

// Bonus ... request logs.
RequestLogHandler logHandler = new RequestLogHandler();
NCSARequestLog requestLog = new NCSARequestLog("/tmp/jetty-yyyy_mm_dd.request.log");
requestLog.setRetainDays(90);
requestLog.setAppend(true);
requestLog.setExtended(false);
requestLog.setLogTimeZone("GMT");
logHandler.setRequestLog(requestLog);

logHandler.setHandler(webapp);

HandlerList handlerList = new HandlerList();
handlerList.addHandler(logHandler);

server.setHandler(handlerList);

server.start();

如果您确实想使用 web.xml,而不是 addFilter() 方法,只需确保您的 webapp 根路径中有一个 WEB-INF/web.xml,并带有以下 xml:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <filter>
        <filter-name>filterName</filter-name>
        <filter-class>com.x.y.z.FilterClass</filter-class>
    </filter>
    <filter-mapping>
        <url-pattern>/test</url-pattern>
        <filter-name>filterName</filter-name>
    </filter-mapping>
</web-app>
于 2013-01-18T14:21:25.787 回答
5

这些ServletContextHandler.addFilter(...)方法只是方法的便利包装ServletHandler.addFilter(...)。只要您只需要一个<url-pattern>,它们非常方便。但是,如果您需要多个模式或选择<servlet-name>改用,您将需要更多类似的东西:

ServletContextHandler context = new ServletContextHandler(
        ServletContextHandler.SESSIONS);

FilterMapping mapping = new FilterMapping();
mapping.setFilterName( "Foobar Filter" );
mapping.setPathSpecs( new String[] { "/foo/*", "/bar/*" } );
mapping.setServletNames( new String[] { "foobar" } );
mapping.setDispatcherTypes(
        EnumSet.of( DispatcherType.INCLUDE,DispatcherType.REQUEST ) ) );

FilterHolder holder = new FilterHolder( FoobarFilter.class );
holder.setName( "Foobar Filter" );

context .getServletHandler().addFilter( holder, mapping );
于 2016-02-08T21:44:46.150 回答
0

更新为 java 11 而不是 javax。使用雅加达。和 11.0.3 用于码头

ServletHolder servletHolder = new ServletHolder(DefaultServlet.class);
servletHolder.setInitParameter("resourceBase","./resource");
servletHolder.setInitParameter("dirAllowed", "false");
servletHolder.setInitParameter("pathInfoOnly", "true");
servletHandler.addServlet(servletHolder, "/api/source/*");
FilterHolder f = new FilterHolder(new MyFilter());
servletHandler.addFilter(MediaFilter.class, "/api/source/*",     
EnumSet.allOf(DispatcherType.class));
于 2021-08-21T18:50:59.830 回答