为嵌入式 tomcat 指定自定义 web.xml

Posted

技术标签:

【中文标题】为嵌入式 tomcat 指定自定义 web.xml【英文标题】:Specify a custom web.xml to an embedded tomcat 【发布时间】:2013-04-05 23:55:56 【问题描述】:

在使用嵌入式 tomcat 实例时,是否可以指定与标准 WEB-INF/web.xml 不同的 web.xml

我想在我的src/test/resources(或其他一些区域)中放置一个web.xml,并在启动嵌入式tomcat时引用该web.xml

这是我现有的启动 tomcat 实例的代码

tomcat = new Tomcat();
String baseDir = ".";
tomcat.setPort(8080);
tomcat.setBaseDir(baseDir);
tomcat.getHost().setAppBase(baseDir);
tomcat.getHost().setAutoDeploy(true);
tomcat.enableNaming();

Context ctx = tomcat.addWebApp(tomcat.getHost(), "/sandbox-web", "src\\main\\webapp");
File configFile = new File("src\\main\\webapp\\META-INF\\context.xml");
ctx.setConfigFile(configFile.toURI().toURL());

tomcat.start();

我正在从一个 tomcat 实例启动这个服务器,我想在运行单元测试时执行以下操作

关闭contextConfigLocation 指定一个自定义ContextLoaderListener,用于设置嵌入式tomcat的父ApplicationContext

这个文件可以这样指定:

File webXmlFile = new File("src\\test\\resources\\embedded-web.xml");

编辑

在经历了很多挫折之后,我意识到无论我做什么,我都无法说服 tomcat 在WEB-INF 中寻找web.xml。看来我必须完全忽略web.xml 并以编程方式设置web.xml 中的项目。

我最终得到了这个配置:

cucumber.xml 用于配置测试

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="applicationContextProvider" class="ca.statcan.icos.sandbox.ApplicationContextProvider"/>

    <bean id="sandBoxDataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
        <property name="url" value="jdbc:hsqldb:mem:testdb;shutdown=true;" />
        <property name="username" value="SA" />
        <property name="password" value="" />
    </bean>

    <!-- Support for JPA related annotation support (@PersistenceUnit and @PersistenceContext) -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <!-- JTA Configuration -->
    <bean id="jtaTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
        init-method="init" destroy-method="close">
        <property name="forceShutdown"><value>true</value></property>
    </bean>

    <bean id="jtaUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp" />

    <bean id="springTransactionManager"
        class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="transactionManager" ref="jtaTransactionManager" />
        <property name="userTransaction" ref="jtaUserTransaction" />
    </bean>

    <!-- JPA Entity Manager configuration -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        lazy-init="true">
        <property name="persistenceUnitName" value="sandBox" />    
        <property name="dataSource" ref="sandBoxDataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="SQL_SERVER" />
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
            </bean>
        </property>
        <property name="jpaPropertyMap">
            <props>
                <prop key="hibernate.archive.autodetection">class</prop>
                <prop key="hibernate.cache.use_second_level_cache">false</prop>
                <prop key="hibernate.cache.use_query_cache">false</prop>
                <!--  Second Level Cache : EHCache in dev
                <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop> -->
                <prop key="hibernate.hbm2ddl.auto">create</prop>
             </props>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <import resource="classpath:META-INF/applicationContext-core.xml" />
    <import resource="classpath:META-INF/applicationContext-web.xml" />

</beans>

applicationContext-core.xml - 配置服务的地方

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd"
    default-autowire="byName">

    <bean id="propertyPlaceholderConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath*:META-INF/fms-local.properties" />
        <property name="systemPropertiesModeName">
            <value>SYSTEM_PROPERTIES_MODE_OVERRIDE</value>
        </property>
    </bean>

    <!-- 
    Classpath scanning to load all the service classes
  -->
    <context:component-scan base-package="ca.statcan"
        use-default-filters="false">
        <context:include-filter type="regex" expression="ca\.statcan\.icos.*\.service\..*Service" />
        <context:include-filter type="regex" expression="ca\.statcan\.icos.*\.builders\..*Builder" />
    </context:component-scan>

        <!-- 
    Spring TransactionManager
  -->
    <tx:advice id="txAdvice" transaction-manager="springTransactionManager">
        <tx:attributes>
            <!-- all methods starting with 'get' are read-only -->
            <tx:method name="get*" read-only="true" propagation="SUPPORTS" isolation="DEFAULT"/>
            <tx:method name="find*" read-only="true" propagation="SUPPORTS" isolation="DEFAULT"/>
            <!-- other methods use the default transaction settings -->
            <tx:method name="*" read-only="false" propagation="REQUIRED" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!-- 
    AOP Weaving for all Service methods
  -->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="icosServiceMethods" expression="execution(* ca.statcan.icos..*.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="icosServiceMethods" />
    </aop:config>

</beans>

自定义 ContextLoaderListener

public class EmbeddedContextLoaderListener extends ContextLoaderListener 

    @Override
    protected WebApplicationContext createWebApplicationContext(ServletContext sc) 
        GenericWebApplicationContext context = new GenericWebApplicationContext(sc);
        context.setParent(ApplicationContextProvider.getApplicationContext());
        return context;
    

    @Override
    protected ApplicationContext loadParentContext(ServletContext servletContext) 
        return ApplicationContextProvider.getApplicationContext();
    

改进的嵌入式 Tomcat 包装器

public class EmbeddedTomcat 
    /** Log4j logger for this class. */
    @SuppressWarnings("unused")
    private static final Logger LOG = LoggerFactory.getLogger(EmbeddedTomcat.class);

    private Tomcat tomcat;

    public void start() 
        try 
            tomcat = new Tomcat();
            String baseDir = ".";
            tomcat.setPort(8080);
            tomcat.setBaseDir(baseDir);
            tomcat.getHost().setAppBase(baseDir);
            tomcat.getHost().setDeployOnStartup(true);
            tomcat.getHost().setAutoDeploy(true);
            tomcat.enableNaming();

            Context context = tomcat.addContext("/sandbox-web", "src\\main\\webapp");
            Tomcat.initWebappDefaults(context);
            configureSimulatedWebXml(context); 

            LOG.info("Starting tomcat in: " + new File(tomcat.getHost().getAppBase()).getAbsolutePath());

            tomcat.start();
         catch (LifecycleException e) 
            throw new RuntimeException(e);
        
    

    public void stop() 
        try 
            tomcat.stop();
            tomcat.destroy();
            FileUtils.deleteDirectory(new File("work"));
            FileUtils.deleteDirectory(new File("tomcat.8080"));
         catch (LifecycleException e) 
            throw new RuntimeException(e);
         catch (IOException e) 
            throw new RuntimeException(e);
        
    

    public void deploy(String appName) 
        tomcat.addWebapp(tomcat.getHost(), "/" + appName, "src\\main\\webapp");
    

    public String getApplicationUrl(String appName) 
        return String.format("http://%s:%d/%s", tomcat.getHost().getName(),
                tomcat.getConnector().getLocalPort(), appName);
    

    public boolean isRunning() 
        return tomcat != null;
    

    private void configureSimulatedWebXml(final Context context) 
        // Programmatically configure the web.xml here

        context.setDisplayName("Sandbox Web Application");

        context.addParameter("org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG", "/WEB-INF/tiles-defs.xml,/WEB-INF/tiles-sandbox.xml");

        final FilterDef struts2Filter = new FilterDef();
        struts2Filter.setFilterName("struts2");
        struts2Filter.setFilterClass("org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter");
        struts2Filter.addInitParameter("actionPackages", "ca.statcan.icos.sandbox.web");
        context.addFilterDef(struts2Filter);    

        final FilterMap struts2FilterMapping = new FilterMap();
        struts2FilterMapping.setFilterName("struts2");
        struts2FilterMapping.addURLPattern("/*");
        context.addFilterMap(struts2FilterMapping);

        context.addApplicationListener("org.apache.tiles.web.startup.TilesListener");
        context.addApplicationListener("ca.statcan.icos.sandbox.EmbeddedContextLoaderListener");

        context.addWelcomeFile("index.jsp");
    

步骤定义

public class StepDefs 

    @Autowired
    protected EmployeeEntityService employeeEntityService;

    @Given("^the following divisions exist$")
    public void the_following_divisions_exist(DataTable arg1) throws Throwable 
        final Employee employee = new Employee(3, "Third", "John", null, "613-222-2223");
        employeeEntityService.persistEmployee(employee);
    

    @Given("^there are no existing surveys$")
    public void there_are_no_existing_surveys() throws Throwable 
    

    @When("^I register a new survey with the following information$")
    public void I_register_a_new_survey_with_the_following_information(DataTable arg1) throws Throwable 
        Capabilities capabilities = DesiredCapabilities.htmlUnit();
        final HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);

        driver.get("http://localhost:8080/sandbox-web/myFirst");
    

    @Then("^the surveys are created$")
    public void the_surveys_are_created() throws Throwable 
        // Express the Regexp above with the code you wish you had
        throw new PendingException();
    

    @Then("^a confirmation message is displayed saying: \"([^\"]*)\"$")
    public void a_confirmation_message_is_displayed_saying(String arg1) throws Throwable 
        // Express the Regexp above with the code you wish you had
        throw new PendingException();
    

动作类

@Results( @Result(name = "success", location = "myFirst.page", type = "tiles") )
@ParentPackage("default")
@Breadcrumb(labelKey = "ca.statcan.icos.sandbox.firstAction")
@SuppressWarnings("serial")
public class MyFirstAction extends HappyfActionSupport 

    private List<Employee> employees;

    @Autowired
    private EmployeeEntityService employeeEntityService;

    @Override
    public String execute() 
        employees = employeeEntityService.getAllEmployee();
        if (employees.size() == 0) 

            // persist data in memory
            final Employee employee1 = new Employee(1, "First", "John", null, "613-222-2222");
            employeeEntityService.persistEmployee(employee1);

            final Employee employee2 = new Employee(2, "Second", "John", null, "613-222-2223");
            employeeEntityService.persistEmployee(employee2);

            employees = employeeEntityService.getAllEmployee();
        
        return SUCCESS;
    

    public List<Employee> getEmployees() 
        return employees;
    


这样,嵌入式 tomcat 可以正确启动,并且在我尝试导航到网页之前一切似乎都很顺利。在StepDefs 类中,EmployeeEntityService 被正确注入。但是,在Action 类中,EmployeeEntityservice 没有被注入(它仍然是null)。

据我所知,我正在为嵌入式 Tomcat 正确设置父 ApplicationContext。那么为什么服务器不使用父上下文来获取EmployeeEntityService

【问题讨论】:

【参考方案1】:

我遇到了类似的问题,使用替代 web.xml 的解决方案比人们想象的要简单:

2 行:

Context webContext = tomcat.addWebapp("/yourContextPath", "/web/app/docroot/");
webContext.getServletContext().setAttribute(Globals.ALT_DD_ATTR, "/path/to/custom/web.xml");

瞧!奇迹发生在org.apache.catalina.startup.ContextConfig#getWebXmlSource

免责声明:已在 Tomcat 7.0.42 上测试

【讨论】:

这看起来确实很简单!我会试一试。谢谢 更简单的选择是:webContext.setAltDDName("/path/to/aternative/web.xml");

以上是关于为嵌入式 tomcat 指定自定义 web.xml的主要内容,如果未能解决你的问题,请参考以下文章

在 Tomcat 中自定义 404 页面(简单配置)

Spring Boot使用嵌入式容器,自定义Filter如何配置?

Spring Boot使用嵌入式容器,那怎么配置自定义Filter呢

Spring-Boot使用嵌入式容器,那怎么配置自定义Filter呢

Tomcat 会话超时 web.xml

自定义filter包