Practical use of @WebServlet and other annotations

In this post, you will learn:

  • How to use @WebServlet annotation?
  • How to use @WebFilter annotation?
  • How to use @webListener annotation?

To demonstrate the practical use of servlet annotations, I have created a web application which have two servlets (ProcessingServlet & ForwardingServlet), a listener (HitCounterListener), a filter (HitCounterFilter) and a HTML page (index.html). When the application is deployed, HitCounterListener sets an attribute named hitCount in the application scope to count the no. of hits of the ProcessingServlet. HitCounterFilter is associated to the ProcessingServlet and is responsible for incrementing its hitCount when a direct request is received for it or a request is forwarded to it. ForwardingServlet is used to simply forwards request to the ProcessingServlet. index.html has two hyper links for sending requests to the ProcessingServlet & ForwardingServlet.

All the servlets, listner and filter use annotations to provide their configuration to the server. There is no web.xml file in the application. To test this application, web or application server must be servlet 3 compatible. Tomcat 7 is a servlet 3 API compatible web server. Here is the source code of the application.

First, the index.html page:

Direct Request to the processingServlet <br/>
InDirect Request to the processingServlet

Second, the HitCounterListener:

package com.techmentro.learningpad;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class HitCounterListener implements ServletContextListener
{

	@Override
	public void contextInitialized(ServletContextEvent e) {
		ServletContext ctx=e.getServletContext();
		ctx.setAttribute("hitCount", 0);
		
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent e) {}
}

Third, the HitCounterFilter:

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;


@WebFilter(urlPatterns={"/processingServlet"},dispatcherTypes={DispatcherType.REQUEST,DispatcherType.FORWARD})
public class HitCounterFilter implements Filter {

	//FilterConfig refrenceVariable to store the reference of the FilterConfig object of the filter
	private FilterConfig config;
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		// Reference of the FilterConfig object provided by the server is saved for future use.
		this.config=config;
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//Reference of the ServletContext is obtained.
		ServletContext ctx=config.getServletContext();
		//obtaining hitCount, incrementing it and resetting.
		Integer hc=(Integer)ctx.getAttribute("hitCount");
		hc++;
		ctx.setAttribute("hitCount", hc);
		//next component is get invoked
		chain.doFilter(request, response);
		
			}

	
	@Override
	public void destroy() {	}

}

Fourth, the ForwardingServlet:

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(urlPatterns={"/forwardingServlet"})
public class ForwardingServlet extends HttpServlet 
{
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		//Obtaining RequestDispatcher for processingServlet
		RequestDispatcher rd=request.getRequestDispatcher("/processingServlet");
		//forwarding request to the processingServlet.
		rd.forward(request, response);
	}
}

Fifth, the ProcessingServlet:

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(urlPatterns={"/processingServlet"},name="S1")
public class ProcessingServlet extends HttpServlet 
{
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
	
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		ServletConfig config=getServletConfig();
		//obtaining hit count
		Integer hc=(Integer)config.getServletContext().getAttribute("hitCount");
		out.println(config.getServletName()+" is invoked "+hc+" time.<br/>");
		out.close();
	}
}

Now, you can check for yourself how configuration is simplified with the help of annotations.


If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

One thought on “Practical use of @WebServlet and other annotations

Leave a Reply

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