Servlet 3 Annotation Example Configuration
A servlet is a Java class that extends the javax.servlet.Servlet
interface. To handle HTTP request you need to extend the javax.servlet.http.HttpServlet
abstraction. Servlets interact with Web clients via a request/response paradigm implemented by the servlet container. In the following tutorial we will show you how to create a servlet 3 annotation example configuration.
Project structure
+--src
| +--main
| +--java
| +--com
| +--memorynotfound
| |--AnnotationServlet.java
| |--resources
| |--webapp
pom.xml
Maven Dependency
Every Servlet Container/Application Server has built in servlet support so you need to set the dependency on provided
. So Maven does not include the library in the final built artifact.
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
Servlet 3 Annotation Configuration
The @WebServlet
annotation is used to define a Servlet Component in a web application. This annotation is specified on a class and contains metadata about the Servlet being declared. The value or urlPattern attribute is required and maps the servlet to an url pattern. It is illegal to use both value and urlPattern attribute together.
package com.memorynotfound;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/example")
public class AnnotationServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
out.write("Example servlet 3 annotation example configuration");
}
}