Annotations in Servlets

Last updated on May 31 2022
Vivek Saxena

Table of Contents

Annotations in Servlets

So far, you have learnt how Servlet uses the deployment descriptor (web.xml file) for deploying your application into a web server. Servlet API 3.0 has introduced a new package called javax.servlet.annotation. It provides annotation types which can be used for annotating a servlet class. If you use annotation, then the deployment descriptor (web.xml) is not required. But you should use tomcat7 or any later version of tomcat.

Annotations can replace equivalent XML configuration in the web deployment descriptor file (web.xml) such as servlet declaration and servlet mapping. Servlet containers will process the annotated classes at deployment time.

The annotation types introduced in Servlet 3.0 are −

Sr.No. Annotation & Description
1 @WebServlet

To declare a servlet.

2 @WebInitParam

To specify an initialization parameter.

3 @WebFilter

To declare a servlet filter.

4 @WebListener

To declare a WebListener

5 @HandlesTypes

To declare the class types that a ServletContainerInitializer can handle.

6 @HttpConstraint

This annotation is used within the ServletSecurity annotation to represent the security constraints to be applied to all HTTP protocol methods for which a corresponding HttpMethodConstraint element does NOT occur within the ServletSecurity annotation.

7 @HttpMethodConstraint

This annotation is used within the ServletSecurity annotation to represent security constraints on specific HTTP protocol messages.

8 @MultipartConfig

Annotation that may be specified on a Servlet class, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type.

9 @ServletSecurity

This annotation is used on a Servlet implementation class to specify security constraints to be enforced by a Servlet container on HTTP protocol messages.

Here we have discussed some of the Annotations in detail.

@WebServlet

The @WebServlet is used to declare the configuration of a Servlet with a container. The following table contains the list of attributes used for WebServlet annotation.

Sr.No. Attribute & Description
1 String name

Name of the Servlet

2 String[] value

Array of URL patterns

3 String[] urlPatterns

Array of URL patterns to which this Filter applies

4 Int loadOnStartup

The integer value gives you the startup ordering hint

5 WebInitParam[] initParams

Array of initialization parameters for this Servlet

6 Boolean asyncSupported

Asynchronous operation supported by this Servlet

7 String smallIcon

Small icon for this Servlet, if present

8 String largeIcon

Large icon for this Servlet, if present

9 String description

Description of this Servlet, if present

10 String displayName

Display name of this Servlet, if present

At least one URL pattern MUST be declared in either the value or urlPattern attribute of the annotation, but not both.

The value attribute is recommended for use when the URL pattern is the only attribute being set, otherwise the urlPattern attribute should be used.

Example

The following example describes how to use @WebServlet annotation. It is a simple servlet that displays the text Hello Servlet.

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebInitParam;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/Simple")

public class Simple extends HttpServlet {




   private static final long serialVersionUID = 1L;




   protected 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>");        

   }  

}

Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

Now try to call any servlet by just running http://localhost:8080/Simple. You will see the following output on the web page.

Hello servlet

@WebInitParam

The @WebInitParam annotation is used for specifying an initialization parameter for a Servlet or a Filter. It is used within a WebFilter or WebSevlet annotations. The following table contains the list of attributes used for WebInitParam annotation.

Sr.No. Attribute & Description
1 String name

Name of the initialization parameter

2 String value

Value of the initialization parameter

3 String description

Description of the initialization parameter

Example

The following example describes how to use @WeInitParam annotation along with @WebServlet annotation. It is a simple servlet that displays the text Hello Servlet and the string value Hello World! which are taken from the init parameters.

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebInitParam;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;




@WebServlet(value = "/Simple", initParams = {

   @WebInitParam(name = "foo", value = "Hello "),

   @WebInitParam(name = "bar", value = " World!")

})

public class Simple extends HttpServlet {




   private static final long serialVersionUID = 1L;




   protected 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.println(getInitParameter("foo"));

      out.println(getInitParameter("bar"));

      out.print("</body></html>");        

   }  

}

Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>;/webapps/ROOT/WEB-INF/classes.

Now try to call any servlet by just running http://localhost:8080/Simple. You will see the following output on the web page.

Hello Servlet

 

Hello World!

@Webfilter

This is the annotation used to declare a servlet filter. It is processed by the container at deployment time, and the corresponding filter applied to the specified URL patterns, servlets, and dispatcher types.

The @WebFilter annotation defines a filter in a web application. This annotation is specified on a class and contains metadata about the filter being declared. The annotated filter must specify at least one URL pattern. The following table lists the attributes used for WebFilter annotation.

Sr.No. Attribute & Description
1 String filterName

Name of the filter

2 String[] urlPatterns

Provides array of values or urlPatterns to which the filter applies

3 DispatcherType[] dispatcherTypes

Specifies the types of dispatcher (Request/Response) to which the filter applies

4 String[] servletNames

Provides an array of servlet names

5 String displayName

Name of the filter

6 String description

Description of the filter

7 WebInitParam[] initParams

Array of initialization parameters for this filter

8 Boolean asyncSupported

Asynchronous operation supported by this filter

9 String smallIcon

Small icon for this filter, if present

10 String largeIcon

Large icon for this filter, if present

Example

The following example describes how to use @WebFilter annotation. It is a simple LogFilter that displays the value of Init-param test-param and the current time timestamp on the console. That means, the filter works like an interface layer between the request and the response. Here we use “/*” for urlPattern. It means, this filter is applicable for all the servlets.

import java.io.IOException;

import javax.servlet.annotation.WebFilter;

import javax.servlet.annotation.WebInitParam;

import javax.servlet.*;

import java.util.*; 




// Implements Filter class




@WebFilter(urlPatterns = {"/*"}, initParams = {

   @WebInitParam(name = "test-param", value = "Initialization Paramter")})

public class LogFilter implements Filter {

  

   public void init(FilterConfig config) throws ServletException {

      // Get init parameter 

      String testParam = config.getInitParameter("test-param");

           

      //Print the init parameter 

      System.out.println("Test Param: " + testParam); 

   }




   public void doFilter(ServletRequest request, ServletResponse response,

      FilterChain chain) throws IOException, ServletException {

                

      // Log the current timestamp.

      System.out.println("Time " + new Date().toString()); 

        

      // Pass request back down the filter chain

      chain.doFilter(request,response);

   }




   public void destroy( ) {

      /* Called before the Filter instance is removed 

      from service by the web container*/

   }

}

Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

Now try to call any servlet by just running http://localhost:8080/Simple. You will see the following output on the web page.

Hello Servlet

 

Hello World!

Now, open the servlet console. There, you will find the value of the init parameter testparam and the current timestamp along with servlet notification messages.

So, this brings us to the end of blog. This Tecklearn ‘Annotations in Servlets’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Servlets and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Annotations in Servlets"

Leave a Message

Your email address will not be published. Required fields are marked *