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

spring– 为嵌入式tomcat指定自定义web.xml,第1张

概述有没有办法在使用嵌入式tomcat实例时从标准WEB-INF / web.xml中指定不同的web.xml?我想在我的src / test / resources(或其他一些区域)中放置一个web.xml,并在启动嵌入式tomcat时引用该web.xml.这是我现有的启动tomcat实例的代码tomcat = new Tomcat(); String bas

有没有办法在使用嵌入式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

applicationContext-core.xml – 配置服务的位置

自定义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

有了这个,嵌入式tomcat正确启动,似乎一切顺利,直到我尝试导航到一个网页.在StepDefs类中,正确注入EmployeeEntityService.但是,在Action类中,不会注入EmployeeEntityservice(它保持为null).

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

最佳答案我遇到了类似的问题,使用替代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上测试

总结

以上是内存溢出为你收集整理的spring – 为嵌入式tomcat指定自定义web.xml全部内容,希望文章能够帮你解决spring – 为嵌入式tomcat指定自定义web.xml所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1260910.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)