[英]spring WebApplicationInitializer configure multiple servlets
[英]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.