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.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--转的更多相关文章
- 关于 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 ...
随机推荐
- iOS开发知识点:理解assign,copy,retain变strong
一..h和.m文件的变化说明 1.对于.h头文件,主要是将属性定义由retain变为strong @property (retain, nonatomic) 变为 @property (strong, ...
- 多重部分和的计数dp
题目大意:有k个大小不同的数字ai,每种各有bi个,求从这些数中选出和为n的排列数 来源:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=1 ...
- [LeetCode OJ] Reorder List—Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
For example,Given {1,2,3,4}, reorder it to {1,4,2,3}. /** * Definition for singly-linked list. * str ...
- JavaScript设计模式之构造函数模式
一.构造函数模式概念 构造函数用于创建特定类型的对象——不仅声明了使用过的对象,构造函数还可以接受参数以便第一次创建对象的时候设置对象的成员值.你可以自定义自己的构造函数,然后在里面声明自定义类型对象 ...
- java获得系统当前日期
package com.web.test; import java.text.ParseException; import java.text.SimpleDateFormat; import jav ...
- ViewData与ViewBag比较
在Asp.net MVC 3 web应用程序中,我们会用到ViewData与ViewBag,对比一下: ViewData ViewBag 它是Key/Value字典集合 它是dynamic类型对像 从 ...
- Bootstrap中的 Typeahead 组件
Bootstrap 中的 Typeahead 组件其实就是嵌入到其中的typeahead.js插件,可以完成输入框的自动匹配功能,在通过一些人工的调整基本可以胜任所有的匹配功能和场景,下面介绍下简单的 ...
- python运维开发之第七天
一.面向对象编程进阶 1.静态方法 @staticmethod 名义上归类管理,实际上跟类没什么关系 在静态方法里,访问不了类或实例中的任何属性 class Static_method(object) ...
- Python报错:SyntaxError: Non-ASCII character '\xe5' in file的解决方法
SyntaxError: Non-ASCII character '\xe5' in file 原因:Python默认是以ASCII作为编码方式的,如果在自己的Python源码中包含了中文(或者其他的 ...
- spring的beans.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...