使用Spark Web框架时如何使用本机Servlet过滤器?

时间:2015-09-17 13:17:46

标签: servlets servlet-filters embedded-jetty spark-java

我正在玩Spark(Java Web框架,而不是Apache Spark)。

我发现定义路由和过滤器真的很好很容易,但是我想在我的路由中应用本机servlet过滤器,但似乎无法找到方法。

更具体地说,我想使用Jetty's DoSFilter这是一个servlet过滤器(与Spark过滤器定义形成对比)。由于Spark使用嵌入式Jetty,我没有web.xml来注册DoSFilter。但是,Spark不会公开服务器实例,所以我找不到以编程方式注册过滤器的优雅方式。

有没有办法将本机servlet过滤器应用到我的路由?

我想把DoSFilter包装在我自己的Spark Filter中,但这似乎是一个奇怪的想法。

1 个答案:

答案 0 :(得分:-1)

你可以这样做:

public class App {
 private static Logger LOG = LoggerFactory.getLogger(App.class);

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

    ServletContextHandler mainHandler = new ServletContextHandler();
    mainHandler.setContextPath("/base/path");

    Stream.of(
            new FilterHolder(new MyServletFilter()),
            new FilterHolder(new SparkFilter()) {{
                this.setInitParameter("applicationClass", SparkApp.class.getName());
            }}
    ).forEach(h -> mainHandler.addFilter(h, "*", null));

    GzipHandler compression = new GzipHandler();
    compression.setIncludedMethods("GET");
    compression.setMinGzipSize(512);
    compression.setHandler(mainHandler);

    Server server = new Server(new ExecutorThreadPool(new ThreadPoolExecutor(10,200,60000,TimeUnit.MILLISECONDS,
                                                                          new ArrayBlockingQueue<>(200),
                                                                       new CustomizableThreadFactory("jetty-pool-"))));

    final ServerConnector serverConnector = new ServerConnector(server);
    serverConnector.setPort(9290);
    server.setConnectors(new Connector[] { serverConnector });

    server.setHandler(compression);
    server.start();

    hookToShutdownEvents(server);

    server.join();
}

private static void hookToShutdownEvents(final Server server) {
    LOG.debug("Hooking to JVM shutdown events");

    server.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {

        @Override
        public void lifeCycleStopped(LifeCycle event) {
            LOG.info("Jetty Server has been stopped");
            super.lifeCycleStopped(event);
        }

    });

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            LOG.info("About to stop Jetty Server due to JVM shutdown");
            try {
                server.stop();
            } catch (Exception e) {
                LOG.error("Could not stop Jetty Server properly", e);
            }
        }
    });
}

/**
 * @implNote {@link SparkFilter} needs to access a public class
 */
@SuppressWarnings("WeakerAccess")
public static class SparkApp implements SparkApplication {

    @Override
    public void init() {
        System.setProperty("spring.profiles.active", ApplicationProfile.readProfilesOrDefault("dev").stream().collect(Collectors.joining()));
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ModocContext.class);
        ctx.registerShutdownHook();
    }

}}