How can a native Servlet Filter be used when using Spark web framework?

依然范特西╮ 提交于 2019-12-04 05:22:20

You can do it like this:

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();
    }

}} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!