I want to use the @WebServlet
annotation in a Java EE webapp which runs on Tomcat 8.
I have read that I need to declare Servlet Version 3.1 in my web.xml
and that my Servlet needs to extend HttpServlet
. I did all that but still the @WebServlet
doesn't work. I am getting a HTTP 404.
I also tried my configuration with metadata-complete="false"
in my web.xml
, but still no success.
Here is my web.xml and Servlet.
The complete sample code can be found on GitHub.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>
<!-- https://mcmap.net/q/541136/-hot-republishing-deploying-of-static-xhtml-files-issues -->
<!-- Put "-1" to disable this feature -->
<context-param>
<param-name>facelets.REFRESH_PERIOD</param-name>
<param-value>1</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<!-- JSF -->
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<!-- CDI -->
<listener>
<listener-class>org.apache.webbeans.servlet.WebBeansConfigurationListener</listener-class>
</listener>
</web-app>
TestServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "TestServlet", urlPatterns = {"*.serve"})
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try (ServletOutputStream out = resp.getOutputStream()) {
out.write("Hello World".getBytes());
out.flush();
}
}
}