Embedded tomcat 7 servlet 3.0 annotations not working--转
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.ContextConfigclass. There's code there that checks for@WebServletannotations, 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--转的更多相关文章
- 关于 tomcat nio connector, servlet 3.0 async, spring mvc async 的关系
tomcat 的 org.apache.coyote.http11.Http11NioProtocol Connector 是一个使用 Java NIO 实现的异步 accept 请求的 connec ...
- 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 ...
- Spring Cloud Gateway报错:Unable to start embedded Tomcat
最近搭建Spring Cloud Gateway时启动项目出现如下报错信息: Error starting ApplicationContext. To display the conditions ...
- gradle中使用嵌入式(embedded) tomcat, debug 启动
在gradle项目中使用embedded tomcat. 最开始部署项目需要手动将web项目打成war包,然后手动上传到tomcat的webapp下,然后启动tomcat来部署项目.这种手动工作通常还 ...
- embedded tomcat context.xml
在网络下载相关的embedded tomcat jar.也可直接在maven中检索. 在main方法中,输入以下代码: //新建tomcat实例 Tomcat tomcat = new Tomcat( ...
- 【tomcat启动失败问题】Unable to start embedded Tomcat
启动spring boot 项目后抛出如下异常: org.springframework.context.ApplicationContextException: Unable to start em ...
- 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 ...
- SpringBoot:springboot整合eureka报错 Unable to start embedded Tomcat
报错信息: org.springframework.context.ApplicationContextException: Unable to start web server; nested ex ...
- [转]Servlet 3.0 新特性详解
原文地址:http://blog.csdn.net/xiazdong/article/details/7208316 Servlet 3.0 新特性概览 1.Servlet.Filter.Listen ...
随机推荐
- zepto源码研究 - callback.js
简要:$.Callbacks是一个生成回调管家Callback的工厂,Callback提供一系列方法来管理一个回调列表($.Callbacks的一个私有变量list),包括添加回调函数, 删除回调函数 ...
- 32.Spring-对象依赖.md
[toc] 1.对象依赖的分类 Spring中,给对象属性赋值的方法: 构造函数 Set方法 p命名空间 自动装配 注解 1.1构造函数 构造方法通过配置文件中constructor-arg标签实现, ...
- 第一个shell编程,输出hello world!
在计算机科学中,Shell俗称壳(用来区别于核),是指“提供使用者使用界面”的软件(命令解析器).它类似于DOS下的command和后来的cmd.exe.它接收用户命令,然后调用相应的应用程序.--- ...
- [Head First设计模式笔记]----命令模式
命令模式定义:将“请求”封装成对象,以便使用不同的请求.队列或者日志来参数化其他对象.命令模式也支持可撤销的操作. 类图: 适用设计方案举例:实现一种遥控器,该遥控器具有七个可编程的插槽(每个都可以指 ...
- Css 描点
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8& ...
- C语言笔记(结构体与offsetof、container_of之前的关系)
关于结构体学习,需要了解:结构体的定义和使用.内存对齐.结构体指针.得到结构体元素的偏移量(offsetof宏实现) 一.复习结构体的基本定义和使用 typedef struct mystruct { ...
- 直接插入排序(Straight Insertion Sort)的C语言实现
原创文章,转载请注明来自钢铁侠Mac博客http://www.cnblogs.com/gangtiexia 直接插入排序(Straight Insertion Sort)的基本思想是将新记录插入到 ...
- 如何把PPT变小|PowerPoint文档减肥的几种方法
使用powerpoint制作幻灯片的过程中,经常出现过这样的情况,制作幻灯片时,出于内容的需要和美观的需要,添加了许多图片和Excel表或者OLE对象,成倍增大了文档的体积,结果导致: 1.页面编辑人 ...
- k-近邻算法理解
左图中,绿色圆要被决定赋予哪个类,是红色三角形还是蓝色四方形?如果K=3,由于红色三角形所占比例为2/3,绿色圆将被赋予红色三角形那个类,如果K=5,由于蓝色四方形比例为3/5,因此绿色圆被赋予蓝色四 ...
- ExtJS 4 MVC架构讲解
大规模客户端应用通常不好实现不好组织也不好维护,因为功能和人力的不断增加,这些应用的规模很快就会超出掌控能力,ExtJS 4 带来了一个新的应用架构,不但可以组织代码,还可以减少实现的内容新的应用架构 ...