Servlets - Annotations


So far, you have figured out how Servlet utilizes the organization descriptor (web.xml document) for conveying your application into a web server. Servlet API 3.0 has presented another package called javax.servlet.annotation. It gives comment types which can be utilized for clarifying a servlet class. On the off chance that you use comment, at that point the arrangement descriptor (web.xml) isn't required. Be that as it may, you should utilize tomcat7 or any later form of tomcat.

Annotations can supplant proportionate XML design in the web sending descriptor record (web.xml, for example, servlet assertion and servlet mapping. Servlet holders will process the explained classes at arrangement time.

The comment types presented in Servlet 3.0 are −

Sr.No. Annotation & Description
1

@WebServlet

To proclaim a servlet.

2

@WebInitParam

To indicate an instatement parameter.

3

@WebFilter

To proclaim a servlet filter.

4

@WebListener

To proclaim a WebListener

5

@HandlesTypes

To proclaim the class types that a ServletContainerInitializer can handle.

6

@HttpConstraint

This comment is utilized inside the ServletSecurity comment to speak to the security limitations to be connected to all HTTP convention techniques for which a relating HttpMethodConstraint component does NOT happen inside the ServletSecurity annotation.

7

@HttpMethodConstraint

This comment is utilized inside the ServletSecurity explanation to speak to security imperatives on explicit HTTP convention messages.

8

@MultipartConfig

Annotation that might be determined on a Servlet class, showing that examples of the Servlet expect demands that adjust to the multipart/structure information MIME type.

9

@ServletSecurity

This comment is utilized on a Servlet execution class to determine security requirements to be implemented by a Servlet holder on HTTP convention messages.

Here we have talked about a portion of the Annotations in detail.

@WebServlet

The @WebServlet is utilized to announce the arrangement of a Servlet with a holder. The accompanying table contains the rundown of qualities utilized for WebServlet annotation.

Sr.No. Attribute & Description
1

String name

Name of the Servlet

2

String[] value

Array of URL designs

3

String[] urlPatterns

Array of URL examples to which this Filter applies

4

Int loadOnStartup

The number esteem gives you the startup requesting clue

5

WebInitParam[] initParams

Array of instatement parameters for this Servlet

6

Boolean asyncSupported

Asynchronous task bolstered by this Servlet

7

String smallIcon

Small symbol for this Servlet, if present

8

String largeIcon

Large symbol 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 design MUST be proclaimed in either the value or urlPattern trait of the explanation, however not both.

The value characteristic is suggested for use when the URL design is the main quality being set, generally the urlPattern trait ought to be used.

Example

The following model depicts how to utilize @WebServlet comment. It is a basic servlet that shows the content 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 standard way and put your class record in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

Now attempt to call any servlet by simply running http://localhost:8080/Simple. You will see the accompanying yield on the web page.

Hello servlet 

@WebInitParam

The @WebInitParam comment is utilized for determining an introduction parameter for a Servlet or a Filter. It is utilized inside a WebFilter or WebSevlet comments. The accompanying table contains the rundown of traits utilized for WebInitParam annotation.

Sr.No. Attribute & Description
1

String name

Name of the introduction parameter

2

String value

Value of the introduction parameter

3

String description

Description of the introduction parameter

Example

The following precedent portrays how to utilize @WeInitParam explanation alongside @WebServlet comment. It is a basic servlet that shows the content Hello Servlet and the string esteem 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 typical way and put your class document in <Tomcat-installationdirectory>;/webapps/ROOT/WEB-INF/classes.

Now attempt to call any servlet by simply running http://localhost:8080/Simple. You will see the accompanying yield on the web page.

Hello Servlet 

Hi World! 

@Webfilter

This is the comment used to announce a servlet channel. It is handled by the holder at arrangement time, and the relating channel connected to the predefined URL designs, servlets, and dispatcher types.

The @WebFilter explanation characterizes a channel in a web application. This comment is determined on a class and contains metadata about the channel being announced. The clarified channel must determine no less than one URL design. The accompanying table records the characteristics utilized for WebFilter annotation.

Sr.No. Attribute & Description
1

String filterName

Name of the channel

2

String[] urlPatterns

Provides cluster of qualities or urlPatterns to which the channel applies

3

DispatcherType[] dispatcherTypes

Specifies the sorts of dispatcher (Request/Response) to which the channel applies

4

String[] servletNames

Provides a variety of servlet names

5

String displayName

Name of the channel

6

String description

Description of the channel

7

WebInitParam[] initParams

Array of instatement parameters for this channel

8

Boolean asyncSupported

Asynchronous task upheld by this channel

9

String smallIcon

Small symbol for this channel, if present

10

String largeIcon

Large symbol for this channel, if present

Example

The following model portrays how to utilize @WebFilter comment. It is a basic LogFilter that shows the estimation of Init-param test-param and the present time timestamp on the reassure. That implies, the channel works like an interface layer between the demand and the reaction. Here we use "/*" for urlPattern. That is to say, this channel is relevant 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 typical way and put your class record in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

Now attempt to call any servlet by simply running http://localhost:8080/Simple. You will see the accompanying yield on the web page.

Hello Servlet 

Hi World! 

Now, open the servlet support. There, you will discover the estimation of the init parameter testparam and the current timestamp alongside servlet notice messages.







© Javacodegeeks 2018 -
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3