gpt4 book ai didi

servlets - 使用Spark Web框架时如何使用 native Servlet筛选器?

转载 作者:行者123 更新时间:2023-12-04 16:13:56 24 4
gpt4 key购买 nike

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

我发现定义路由和过滤器确实很好,而且很容易,但是我希望将 native servlet过滤器应用于路由,似乎找不到找到这种方法的方法。

更具体地说,我想使用Jetty's DoSFilter,它是一个servlet过滤器(与Spark Filter定义相反)。由于Spark使用的是嵌入式Jetty,因此我没有web.xml来注册DoSFilter。但是,Spark不会公开服务器实例,因此我也找不到一种以编程方式注册筛选器的优雅方法。

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

我曾想将DoSFilter封装在自己的Spark过滤器中,但这似乎是一个奇怪的想法。

最佳答案

您可以这样做:

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

}}

关于servlets - 使用Spark Web框架时如何使用 native Servlet筛选器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32631294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com