您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

嵌入式tomcat 7 Servlet 3.0注释不起作用

嵌入式tomcat 7 Servlet 3.0注释不起作用

好吧,我终于通过查看Tomcat7源代码解决了它,即在处理EmbeddedTomcat和Servlet 3.0批注的单元测试中。

基本上,您必须像这样启动Embedded Tomcat 7,以使其了解带注释的类:

String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);

StandardContext ctx = (StandardContext) tomcat.addWebapp("/embeddedTomcat",
                new File(webappDirLocation).getAbsolutePath());

//declare an alternate location for your "WEB-INF/classes" dir:     
File additionWebInfClasses = new File("target/classes");
VirtualDirContext resources = new VirtualDirContext();
resources.setExtraResourcePaths("/WEB-INF/classes=" + additionWebInfClasses);
ctx.setResources(resources);

tomcat.start();
tomcat.getServer().await();

为了清楚起见,我应该提到这适用于标准的Maven项目,在该项目中可以在以下位置找到“ Web资源”(例如静态和动态页面,WEB-INF目录等):

[您项目的根目录] / src / main / webapp

你的班级被编译成

[您项目的根目录] /目标/类

(这样,您将拥有[您的项目的根目录] / target / classes / [某些软件包] /SomeCompiledServletClass.class)

对于其他目录布局,需要相应地更改这些位置。

====更新:嵌入式Tomcat 8 ====

感谢@kwak注意到这一点。

API进行了一些更改,以下是使用嵌入式Tomcat 8时上述示例的变化:

String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);

StandardContext ctx = (StandardContext) tomcat.addWebapp("/embeddedTomcat",
                new File(webappDirLocation).getAbsolutePath());

//declare an alternate location for your "WEB-INF/classes" dir:     
File additionWebInfClasses = new File("target/classes");
WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
ctx.setResources(resources);

tomcat.start();
tomcat.getServer().await();
Jave 2022/1/1 18:15:10 有395人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶