In the following tutorial we will show you how to create a servlet 3.0 annotation example. The Java Servlet API 3.0 introduces a new package called javax.servlet.annotation. The javax.servlet.annotation provides annotation types which can be used for annotating a servlet class. This is first post of series of Java Servlet Tutorial. This series tutorial will provide you full knowledge about Servlet 3.0.
Table of content:
1. Introduction to Servlet annotation
2. Project structure
3. Maven Dependency
4. Servlet 3.0 Annotation
5. Deploy war file on application server
Servlet annotation
The annotation types introduced in Servlet 3.0 are:
1 2 3 4 5 6 7 8 9 |
@HandlesTypes @HttpConstraint @HttpMethodConstraint @MultipartConfig @ServletSecurity @WebFilter @WebInitParam @WebListener @WebServlet |
Now we start to build Servlet 3.0 Annotation Example.
Project structure
The project structure should be such as the figure below:

Note: This example is using servlet 3.0 annotation configuration so the servlet is not required to add a web.xml.
Maven Dependency
We should add depedency for servlet such as below.
1 2 3 4 5 6 7 8 |
<dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> <!-- Maven does not include the library in the final built artifact --> </dependency> </dependencies> |
Servlet Container or Application Server has built in servlet support so we need to set the scope is provided.
Servlet 3.0 Annotation
The main focus of this example is the AnnotationServletDemo servlet. You see the @WebServlet annotation that is used to define a Servlet Component in a web application. The value attribute is required and maps the servlet to an url pattern. Here the value is “/example”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javabycode; 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 request, HttpServletResponse response) throws ServletException, IOException { PrintWriter prinOut = response.getWriter(); prinOut.write("Hello, This is the first servlet 3 annotation example"); } } |
Deploy war file on application server.
After push the file war and run application server we access the address http://localhost:8080/annotation-servlet3/example. The result should be such as the figure below.

That’s all. Now you could base on this example to build your own servlet example. Welcome any opinion from your side. You can also find other servlet example in the series of Java Servlet Example.
Download complete source code, please click link below
Servlet-3-Annotation-Example.zip (364 downloads)