繁体   English   中英

WebApplicationInitializer中的多个Servlet

[英]Multiple Servlets in WebApplicationInitializer

我试图在WebApplicationInitializer设置多个servlet,一个用于默认请求(使用DispatcherServlet触发jsp并返回html,另一个使用定制的StaticServlet来处理静态资源。令我困惑的是如何申请将请求发送到正确的servlet的路由,实际上从未调用过静态servlet之一来解析请求似乎证实了我的怀疑。到目前为止,这是我在WebApplicationInitializer上拥有的代码:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    servletContext.setSessionTrackingModes(
        Collections.<SessionTrackingMode>emptySet());

    // Create the 'root' Spring application context
    // which will contain the application components
    AnnotationConfigWebApplicationContext rootContext
        = new AnnotationConfigWebApplicationContext();
    rootContext.register(RootConfig.class);

    // Manage the lifecycle of the root application context
    servletContext.addListener(new ContextLoaderListener(rootContext));

    // Create the dispatcher servlet's Spring application context
    // to contain dispatched beans such as controllers
    AnnotationConfigWebApplicationContext dispatcherContext
        = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(DispatcherConfig.class);

    // Register and map the dispatcher servlet under /
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
        "dispatcher",
        new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

    // Register and map the static dispatcher servlet under /static/*
    ServletRegistration.Dynamic staticDispatcher = servletContext.addServlet(
        "staticDispatcher",
        new FileServlet());

    staticDispatcher.setLoadOnStartup(1);
    staticDispatcher.setInitParameter("basePath", "/static/fonts/");
    staticDispatcher.addMapping("/static/*");

静态Servlet不需要Configuration (是一个基本HttpServlet ),但是令我困扰的是我使用两个ServletRegistration来定义两个不同的映射。 有没有一种方法可以使用相同的方法并定义到特定servlet的映射? 还是应该在另一个级别上完成映射(可能是rootContext的Listener)? 我试图环顾四周,但似乎没有人解决或以编程方式设置多个servlet时遇到任何问题(可能)。

我为什么对静态Servlet没有任何帮助?

编辑:

这是我的一个.jsp文件中的静态文件请求,应该通过FileServlet

<style type="text/css">
     @font-face {
        font-family: 'DinWeb';
        src: url(/static/fonts/DINWeb.eot?) format('eot'), url(/static/fonts/DINWeb.woff)  format('woff'), url(/static/fonts/DINComp.ttf) format('truetype');
        font-weight: normal;
    }
</style>

我希望将请求重定向到FileServlet (因为url以/ static /开头),然后从那里进行操作/管理,以便它返回字体(或文件或其他媒体)

创建了一个替代解决方案:无需实现两个DispactherServlet (或一个或另一个),只需实现一个Servlet和一个Filter侦听所有请求,并处理以静态开头的URL。

在我的代码中,添加了以下两行:

FilterRegistration filterReg = servletContext.addFilter("staticFilter",     StaticFilesFilter.class);
filterReg.addMappingForUrlPatterns(null, false, "/*");

并完全删除了第二个定制的servlet。 对于过滤器,此链接非常有用(只需单击下载即可查看过滤器实现本身的java文件)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM