servlet

Java Servlet Annotations Example

Communication between the Servlets is an important task to the programmer. In this tutorial, we will see how the Servlet annotations can replace the equivalent XML configuration in the web deployment descriptor file (web.xml).

1. Introduction

The Servlet API 3.0 introduces a new package called javax.servlet.annotation which provides the annotation types which can be used for annotating a Servlet class. The annotations can replace the equivalent XML configuration in the web deployment descriptor file (i.e. web.xml) such as Servlet Declaration and Servlet Mapping. Servlet Containers will process the annotated classes at the time of application deployment.

 
The different types of annotations introduced in Servlet 3.0 are:

  • @HandlesTypes
  • @HttpConstraint
  • @HttpMethodConstraint
  • @MultipartConfig
  • @ServletSecurity
  • @WebFilter
  • @WebInitParam
  • @WebListener
  • @WebServlet

The @WebServlet annotation is used for declaring a Servlet class (i.e. the Servlet class must extend from the HttpServlet class) and configuring the mapping for it. Here are some examples of using the @WebServlet annotation:

  • The simplest way to declare a Servlet

Here the MyServlet servlet is mapped to the /processForm URL pattern. When accessing this servlet, it will return a Hello message.

@WebServlet("/processForm")
public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.getWriter().println("Hello");
    }
}
  • Declare a Servlet with additional information

Here the MyServlet servlet is declared with additional information such as name and description.

@WebServlet(
    name = "MyServlet",
    description = " This is my first annotated servlet",
    urlPatterns = {"/processServlet"}
)
public class MyServlet extends HttpServlet {
    // Servlet Code Here 
}
  • Declare a Servlet with multiple URL patterns

Here the MyServlet servlet is mapped to three different URL patterns i.e. /foo, /bar, and /cool.

@WebServlet(urlPatterns = {"/foo", "/bar", "/cool"})
public class MyServlet extends HttpServlet {
    // Servlet Code Here
}
  • Declare a Servlet with some init parameters

Here we declare the ImageUploadServlet mapped by the URL pattern: /imageUpload and specify the two init parameters i.e. saveDir and allowedTypes. The Servlet’s doGet() method retrieves the values of these parameters and prints them out to the client.

@WebServlet(
        urlPatterns = "/imageUpload",
        initParams = {
            @WebInitParam(name = "saveDir", value = "D:/FileUpload"),
            @WebInitParam(name = "allowedTypes", value = "jpg, jpeg, gif, png")
        }
)
public class ImageUploadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String saveDir = getInitParameter("saveDir"), 
             fileTypes = getInitParameter("allowedTypes");
 
        PrintWriter writerObj = response.getWriter();
        writerObj.println("saveDir?= " + saveDir);
        writerObj.println("fileTypes?= " + fileTypes);
    }
}
  • Declare a Servlet with asynchronous operation mode and load-on-startup order

Here we declare the servlet StartupServlet with loadOnStartup = 1. This means that this servlet is initialized automatically by the Servlet container when the server is being started (and the message in the init() method will be printed). Here we will also specify whether the Servlet supports the Asynchronous Mode or not.

@WebServlet(
        urlPatterns = "/myController",
        loadOnStartup = 1,
        asyncSupported = true
)
public class StartupServlet extends HttpServlet {   
    public void init(ServletConfig config) {
        loggerObj.debug("My Servlet Has Been Initialized ….!");
    }
     
    // Servlet Code Here
}

2. Example of simple Servlet by Annotation

There is given the simple example of a Servlet class with annotations.

Simple.java

package com.jcg.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Simple")  
public class Simple extends HttpServlet {  

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.print("<html><body>");
		out.print("<h3>Hello Servlet</h3>");
		out.print("</body></html>");
	}
}

Now run the project on Tomcat7 and if everything goes right developers will get the following screen.

Fig.1: Servlet Annotations Application Output
Fig.1: Servlet Annotations Application Output

That’s all for this post. Happy Learning!!

3. Conclusion

In this section, developers learned how the Servlet annotations can replace the equivalent XML configuration in the web deployment descriptor file. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.

4. Download the Eclipse Project

This was an example of Servlet Annotations.

Download
You can download the full source code of this example here: Servlet Annotation

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button