2016-05-10 22 views
1

我在Spring上有一個應用程序,並使用Java Configs來配置和初始化我的應用程序,所以我沒有web.xml。這裏是我的網頁初始化的樣子,在Spring中混合web.xml和AbstractAnnotationConfigDispatcherServletInitializer

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 
    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     super.onStartup(servletContext); 
    } 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class<?>[]{PublicApiConfig.class, MobileConfig.class}; 
    } 

    @Override 
    protected String[] getServletMappings() { 
     return new String[]{"/*"}; 
    } 

    @Override 
    protected Filter[] getServletFilters() { 
     CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); 
     characterEncodingFilter.setEncoding("UTF-8"); 
     LoggingFilter loggingFilter = new LoggingFilter(); 
     return new Filter[]{characterEncodingFilter, loggingFilter}; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return new Class<?>[0]; 
    } 
} 

我需要實現Tomcat會話複製,併爲目的的緣故,我需要有應用程序distributable。使用傳統的web.xml,我可以添加<distributable/>屬性,就是這樣。但據我所知,沒有辦法通過Java Configs來做到這一點。

我的問題是,如果有可能有混合的web.xml和java配置,例如有

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns="http://java.sun.com/xml/ns/javaee" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
     version="3.0"> 

    <distributable/> 

</web-app> 

並將其包含在WebInitializer中。

+0

是的,你可以混合使用它們,但是我沒有得到的是,即使有這個web.xml,你也會得到web.xml不存在的錯誤? –

回答

1

您可以使用TomcatEmbeddedServletContainerFactory,有

@Override 
public void customize(Context context){ 
      context.setDistributable(true); 
     } 

你會發現在這個線程一個完整的代碼示例 spring-boot-application-with-embedded-tomcat-session-clustering

編輯:我不是在這種情況下使用Spring啓動,並TomcatEmbeddedServletContainerFactory是不可用

javadoc的WebApplicationInitializer說,它可能一起使用w ith web.xml:

WEB-INF/web.xml和WebApplicationInitializer的使用不是互斥的;例如,web.xml可以註冊一個servlet,而WebApplicationInitializer可以註冊另一個。初始化程序甚至可以通過諸如ServletContext#getServletRegistration(String)之類的方法修改在web.xml中執行的註冊。

+0

我沒有在這種情況下使用Spring Boot,並且TomcatEmbeddedServletContainerFactory不可用 – vtor

1

根據Servlet 3.0規範,只要web-app版本> = 3.0且metadata-complete屬性爲false(默認),就可以將web.xml與Programmatic servlet註冊混合。使用你當前的配置,它應該可以工作

+1

感謝您的迴應。但是,如何在WebInitializer類中包含這個web-fragment.xml文件?通過導入? – vtor

相關問題