嵌入式 tomcat 7 servlet 3.0 注释不起作用== 更新 ==
我有一个精简的测试项目,其中包含一个Servlet版本3.0,用这样的注释声明:
@WebServlet("/test")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = -3010230838088656008L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.getWriter().write("Test");
response.getWriter().flush();
response.getWriter().close();
}
}
我还有一个网络.xml文件,如下所示:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>g1.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testWebXml</url-pattern>
</servlet-mapping>
</web-app>
我尝试过使用嵌入式Tomcat 7进行JUnit测试。当我启动嵌入式Tomcat时,我只能通过web.xml(/testWebXml)中声明的url模式访问servlet。如果我尝试通过注释(/test)声明的url模式访问它,则找不到404页面。
这是我的测试的代码:
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
tomcat.addWebapp("/jerseyTest", new File(webappDirLocation).getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
为了确保我正确设置了我的项目,我还安装了一个真正的Tomcat 7并部署了战争。这一次,web.xml声明的url和我的servlet的注释url都可以正常工作。
所以我的问题是:有没有人知道如何让嵌入式Tomcat 7考虑到我的Servlet 3.0注释?
我还应该声明这是一个 Maven 项目,pom.xml包含以下依赖项:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>7.0.29</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>7.0.29</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>7.0.29</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
== 更新 ==
这里有一个似乎与此类似的问题(除了不起作用的Servlet 3.0注释是在Lister上,而不是Servlet上),它有一个建议的修复方法:
https://issues.apache.org/bugzilla/show_bug.cgi?id=53903
我试过了,但它不起作用:
将嵌入式 Tomcat 启动代码更改为:
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.enableNaming();
tomcat.setPort(8080);
Context ctx = tomcat.addWebapp(tomcat.getHost(), "/embeddedTomcat", new File(webappDirLocation).getAbsolutePath());
((StandardJarScanner) ctx.getJarScanner()).setScanAllDirectories(true);
tomcat.start();
tomcat.getServer().await();
我尝试过的其他事情,也没有成功:
专门设置 metadata-complete=“false” 在 web.xml“web-app” 标记
将 Maven 依赖项更新到版本 7.0.30
调试类。那里有代码检查注释,只是它永远不会被执行(第2115行)。这可能是找到问题根源的好方法,但是这个类非常大,我现在没有时间这样做。也许如果有人愿意看看这个类是如何工作的,以及在什么条件下(配置参数)它能正确检查你项目的类的注释,它可能会得到一个有效的答案。
org.apache.catalina.startup.ContextConfig
@WebServlet