Grizzly + Static Content + Servlet Filter

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-05 08:45:33

问题


I can get Grizzly to serve static content

I can create the servlet filter to filter a named servlet

But I can't get the servlet filter to filter the static content. How do I do that?

Here is the code I have so far:

WebappContext webappContext = new WebappContext("grizzly web context", "");
FilterRegistration authFilterReg = webappContext.addFilter("Authentication Filter", org.package.AuthenticationFilter.class);

// If I create a ServletContainer, I can add the filter to it like this:
// authFilterReg.addMappingForServletNames(EnumSet.allOf(DispatcherType.class), "servletName");

HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(BASE_URI);
webappContext.deploy(httpServer);

// This works, but the content does not go through the authentication filter above
httpServer.getServerConfiguration().addHttpHandler(new StaticHttpHandler(absolutePath), "/static");

回答1:


The ServletFilters registered as part of WebappContext (Web application) will be executed only for requests related to this WebappContext (Web application).

So, one of the solutions I see is to register DefaultServlet [1] on the WebappContext and use it instead of StaticHttpHandler. Something like:

ArraySet<File> set = new ArraySet<File>(File.class);
set.add(new File(absolutePath));
ServletRegistration defaultServletReg = webappContext.addServlet("DefaultServlet", new DefaultServlet(set) {});
defaultServletReg.addMapping("/static");

[1] https://github.com/GrizzlyNIO/grizzly-mirror/blob/2.3.x/modules/http-servlet/src/main/java/org/glassfish/grizzly/servlet/DefaultServlet.java



来源:https://stackoverflow.com/questions/21128415/grizzly-static-content-servlet-filter

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