Question:

I have a stripped down test project which contains a Servlet version 3.0, declared with annotations like so:

    @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();
}
}

I also have a web.xml file like so:

<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>

I've tried to make a JUnit test using Embedded Tomcat 7. When I start the Embedded Tomcat I can only access the servlet via the url-pattern declared in web.xml (/testWebXml). If I try to access it via the url-pattern declared via annotation (/test) it sais 404 page not found.

Here's the code for my test:

    String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080); tomcat.addWebapp("/jerseyTest", new File(webappDirLocation).getAbsolutePath()); tomcat.start();
tomcat.getServer().await();

Just to make sure I've set up my project correctly, I've also installed an actual Tomcat 7 and deployed the war. This time, both web.xml declared url and annotation url for my servlet work ok.

So my question is: does anyone know how to make Embedded Tomcat 7 take into account my Servlet 3.0 annotations?

I should also state that it's a Maven project, and the pom.xml contains the following dependencies:

    <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>

== UPDATE ==

Here's an issue that seems similar to this (except the Servlet 3.0 annotation that is not working is on Listener, not Servlet), which has a suggested fix:

https://issues.apache.org/bugzilla/show_bug.cgi?id=53903

I've tried it and it didn't work:

Changed the Embedded Tomcat start code to:

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();

Other things I've tried, also without success:

  • specifically setting metadata-complete="false" in web.xml "web-app" tag

  • updating the Maven dependencies to version 7.0.30

  • debugging the org.apache.catalina.startup.ContextConfig class. There's code there that checks for @WebServlet annotations, it's just that it never gets executed (line 2115). This may be a good way to get to the root of the issue, but the class is pretty big, and I don't have time to do this now. Maybe if someone would be willing to look how this class works, and under which conditions (config params) does it get to correctly check your project's classes for that annotation, it might get to a valid answer.

Answer:

Well I finally solved it by looking in the Tomcat7 sources, namely in the unit tests that deal with EmbeddedTomcat and servlet 3.0 annotations.

Basically, you must start your Embedded Tomcat 7 like this to make it aware of your annotated classes:

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();

For the sake of clarity I should mention that this works for a standard Maven project where your "web resources" (such as static and dynamic pages, WEB-INF directory etc) are found in:

[your project's root dir]/src/main/webapp

and your classes get compiled into

[your project's root dir]/target/classes

(such that you'd have [your project's root dir]/target/classes/[some package]/SomeCompiledServletClass.class)

For other directories layouts, these locations need to be changed accordingly.

==== UPDATE: Embedded Tomcat 8 ====

Thanks to @kwak for noticing this.

The APIs have changed a bit, here how the above example changes when using Embedded 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();

原文地址:http://stackoverflow.com/questions/11669507/embedded-tomcat-7-servlet-3-0-annotations-not-working/12688842#12688842

Embedded tomcat 7 servlet 3.0 annotations not working--转的更多相关文章

  1. 关于 tomcat nio connector, servlet 3.0 async, spring mvc async 的关系

    tomcat 的 org.apache.coyote.http11.Http11NioProtocol Connector 是一个使用 Java NIO 实现的异步 accept 请求的 connec ...

  2. Spring boot Unable to start embedded Tomcat报错 java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()

    Spring boot Unable to start embedded Tomcat 报错 java.lang.NoSuchMethodError: javax.servlet.ServletCon ...

  3. Spring Cloud Gateway报错:Unable to start embedded Tomcat

    最近搭建Spring Cloud Gateway时启动项目出现如下报错信息: Error starting ApplicationContext. To display the conditions ...

  4. gradle中使用嵌入式(embedded) tomcat, debug 启动

    在gradle项目中使用embedded tomcat. 最开始部署项目需要手动将web项目打成war包,然后手动上传到tomcat的webapp下,然后启动tomcat来部署项目.这种手动工作通常还 ...

  5. embedded tomcat context.xml

    在网络下载相关的embedded tomcat jar.也可直接在maven中检索. 在main方法中,输入以下代码: //新建tomcat实例 Tomcat tomcat = new Tomcat( ...

  6. 【tomcat启动失败问题】Unable to start embedded Tomcat

    启动spring boot 项目后抛出如下异常: org.springframework.context.ApplicationContextException: Unable to start em ...

  7. embedded tomcat运行java web,Unable to compile class for JSP

    环境 eclipse:4.5.2 jre:1.8 java project compiler:1.8 embedded tomcat:7.0.32 可以正常启动,但是访问时,会报错. HTTP Sta ...

  8. SpringBoot:springboot整合eureka报错 Unable to start embedded Tomcat

    报错信息: org.springframework.context.ApplicationContextException: Unable to start web server; nested ex ...

  9. [转]Servlet 3.0 新特性详解

    原文地址:http://blog.csdn.net/xiazdong/article/details/7208316 Servlet 3.0 新特性概览 1.Servlet.Filter.Listen ...

随机推荐

  1. iOS开发之Quartz2D详解

    1. 什么是Quartz2D? Quartz 2D是一个二维绘图引擎,同时支持iOS和Mac系统 Quartz 2D能完成的工作 绘制图形 : 线条\三角形\矩形\圆\弧等 绘制文字 绘制\生成图片( ...

  2. 【OpenSSL】创建证书

    [-] 1生成根证书 1 生成RSA私钥 2 生成证书请求 3 签发自签名证书 2 生成用户证书 1 生成RSA私钥 2 生成证书请求 3 签发证书   1)生成根证书 1.1) 生成RSA私钥 op ...

  3. Java面试——基础

    1,作用域,Java只有public,protect,private,默认是default相当于friendly 作用域 当前类          同一package 子类            其它 ...

  4. 按钮制作技巧(css精灵效果)-高级版

    [转自己以前的文章] 无论用什么语言,大家敲程序的时候多多少少都会遇到做按钮的时候.今天分享一个之前学做按钮的技巧,有人叫做css精灵效果. 通常做按钮的思路都用附图中的第一种:两张图片交互的形式,让 ...

  5. 04_RHEL7.1忘记root密码

    在开机进入启动项时,选择需要重设密码的那个启动项 按e进入编辑模式,找到rhgb和quiet参数(几乎在最下面),替换为 init=/bin/sh 按ctrl+X不需密码进入shell 以rw的方式重 ...

  6. js ie浏览器下的选中操作

    最近在学习jquery  好多英文网站,制作一个网站的副本,可以主动地学习.好像给自己的网站添加一个小词典,就像沪江小d那样. js试了好几种方法 实在不行,网上搜索了下 ,用到了浏览器开发.本篇文章 ...

  7. jquery animate函数实现

    jquery animate 函数 实现动画效果 参数一 比如高度宽度 之类的:'-=50' 参数二 速度之类 <html xmlns="http://www.w3.org/1999/ ...

  8. python3数据类型--数字

    数字 Python数字数据类型用于存储数值.数字数据类型是不允许改变的,所以如果改变数字数据类型的值,将重新分配内存空间. 以下实例在变量赋值时Number对象被创建: #!/usr/bin/env ...

  9. MLlib-聚类

    聚类 例子 流聚类 例子 聚类 MLlib支持k-means聚类,一种最常用的聚类方法,将数据点聚成指定数据的簇.MLlib实现了一种k-means++的并行变种,叫做kmeansII.MLlib的实 ...

  10. Scut:参数导入方式(有遗留疑问)

    先上一段代码: public EnvironmentSetting() { var appServer = GetServerSection(); var protocol = GetProtocol ...