Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Using ServletContextListener in Java

In this article we will see what is ServletContextListener and also how to use it in Java web applications.

There are several kind of listener objects are available with their specific usage. One of these objects is ServletContextListener object that provides the access of the data proviced by the ServletContext object into its whole application, once an application is deployed onto the web or web application server.ServletContextListener may be configured using annotations or the servlet xml configuraiton file named web.xml. In this aritcle, we will have a look on both of the stragies of accessing ServletContextListener into our web application.

ServletContextListener object in detail:

A ServletContext object is initialized once, while a web application is being deployed and this object may be accessed into the same application from any where. To access this object, an event is occurred that get the data associated with this object and start a new event to handle that data. To listen data from this object, there is an object available named “ServletContextListener” that listens data from these kind of objects. This listener object uses two methods to handle this event as:

public void contextInitialized(ServletContextEvent event)
And
public void contextDestroyed(ServletContextEvent event)

Now let’s go with an example that will create ServletContext object that will be access using the ServletContextListener object as shown below in the given example.

Listing 1: Student.java

public class Student {
	private String name;
	private String add;
	
	public Student(String name, String add){
		this.name = name;
		this.add = add;
	}
	
	public String getAdd(){
		return add;
	}
	
	public String getName(){
		return name;
	}
}

Listing 1 defines a java class “Student” that declares two class member variables name and add with its getter() methods and one parameterized constructor that accepts two String type variable to initialized its class member variables name and add respectively.

Now let’s creates two instances of this class into the another java class files “ContextListenerExample.java” that is defined into Listing 2 as:

Listing 2: ContextListenerExample.java

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

public class ContextListenerExample implements ServletContextListener {
	public void contextInitialized(ServletContextEvent e){
		ServletContextcntxt = e.getServletContext();
		Student obj1 = new Student("Umesh", "Noida");
		Student obj2 = new Student("Pooja", "Delhi");
		cntxt.setAttribute("obj1", obj1);
		cntxt.setAttribute("obj2", obj2);
	}
	public void contextDestroyed(ServletContextEvent e){
			System.out.println("Destroyed");
	}
}

Listing 2 defines a java class “ContextListenerExample” that defines two methods contextInitialized() and contextDestroyed(). The contextInitialized() method creates aServletContext class instance to setup ServletContext type two variables. Hence, these two variables may be access into the entire application, once this web application is deployed. Two instances of Students class type are created and these instances are assigned to ServletContext class instance using setAttribute() method to create two context type variables.Method contextDestroyed() is called to remove these context variable, if we are not required to access these context variables.

Now, let’s defines one more java class that is used to access these context variables by listing ServletContextListener event as listed into Listing 3:

Listing 3: ListenerExample.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ListenerExample extends HttpServlet{
	
	public void doGet(HttpServletRequestreq, HttpServletResponse res)
	throwsIOException, ServletException{
	res.setContentType("text/html");
		PrintWriter pw = res.getWriter();
		pw.println("<h2>Student's Name and Address</h2>");
		pw.println("");
		Student stu = (Student)getServletContext().getAttribute("obj1");
		Student stu1 = (Student)getServletContext().getAttribute("obj2");
		pw.println("\n<b>"+stu.getName()+"</b> lives in <b>"+stu.getAdd()+"</b><br>");
		pw.println("\n<b>"+stu1.getName()+"</b> lives in <b>"+ stu.getAdd()+"</b><br>");
	}
	
}

Listing 3 defines “ListenerExample.java” class file that defines a servlet to be access by the web browser. The servlet class accesses the context variables and displays the data into the web pages loaded. This class extends HttpServlet class and defines a method doPost() that throws exception of type IOException and ServletException classes and accepts two parameters of HttpServletRequest and HttpServletResponse classes respectively.This method defines the response context type to “text/html” and creates an instance of type PrintWrite class that will be used write into the web page.

To access data from the context variables, call a method of class GenericServletgetServletContext() this method return a reference of ServletContext that helps to call the method getAttribute() of class ServleContext class. This method accepts an argument as context variable name that was created.

Now, let’s define a servlet configuration file web.xml as listed in Listing 4:

Listing 4: web.xml

<web-app>
	<listener>
		<listener-class>ContextListenerExample</listener-class>
	</listener>
	<servlet>
		<servlet-name>ListenerExample</servlet-name>
		<servlet-class>ListenerExample</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>ListenerExample</servlet-name>
		<url-pattern>/ListenerExample</url-pattern>
	</servlet-mapping>
</web-app>

Listing 4 defines the deployment descriptor that defines a set of tags to configure servlet mapping and listener tag are used to define the listener class. The servlet mapping is mapped to “/ListenerExample” that hits to servlet class “ListenerExample” defined into the default package.

The above configuration was made using the deployment descriptor.This web application can be written using the annotation configuration. The annotation can be used to configure the web servlets as well as the linstener of the web application.In this way, there are a set of annotation classes that will be used to write servlet and listener classes without using the deployment descriptor file.

A annotation @WebServlet() is used to define a servlet configuration and the @WebListener is used to defines a ServletContextListener into an application. The @WebServlet is defined into the annotation class “javax.servlet.annotation.WebServlet” and @WebListener is defined into the java class “javax.servlet.annotation.WebListener”

So, The above servlet class and the listener classes can be re-defines as listed into Listing 5 and Listing 6 respectively.

Listing 5: ContextListenerExample.java

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

@WebListener
public class ContextListenerExample implements ServletContextListener {
	public void contextInitialized(ServletContextEvent e){
		ServletContextcntxt = e.getServletContext();
		Student obj1 = new Student("Umesh", "Noida");
		Student obj2 = new Student("Pooja", "Delhi");
		cntxt.setAttribute("obj1", obj1);
		cntxt.setAttribute("obj2", obj2);
	}
	public void contextDestroyed(ServletContextEvent e){
			System.out.println("Destroyed");
	}
}

Listing 5 re-defines the java class ContextListenerExample.java that defines the listener information to the web application or web server about the listener class definition using annotation @WebListener.

Listing 6: ListenerExample.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
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(value="/ListenerExample")
public class ListenerExample extends HttpServlet{
	
	public void doGet(HttpServletRequestreq, HttpServletResponse res)
	throws IOException, ServletException{
	res.setContentType("text/html");
		PrintWriter pw = res.getWriter();
		pw.println("<h2>Let's Access Name of Student's Name and Address</h2>");
		pw.println("");
		Student stu = (Student)getServletContext().getAttribute("obj1");
		Student stu1 = (Student)getServletContext().getAttribute("obj2");
		pw.println("\n<b>"+stu.getName()+"</b> lives in <b>"+stu.getAdd()+"</b><br>");
		pw.println("\n<b>"+stu1.getName()+"</b> lives in <b>"+ stu.getAdd()+"</b><br>");
	}
	
}

Listing 6 re-define ListenerExample.java class file that defines the servlet mapping configuration using annotation @WebServlet(value=”/ListenerExample”,name = “Listener-Example”)

Required Tools and Applications:

There is are list of tools and applications required to run above example as listed:

  • Eclipse IDE(Eclipse JUNO)
  • Application or web server (Tomcat 7)
  • JDK Run time Environment (JDK 1.7)
  • Servlet Jar files

Required Directory Structure:

Directory Structure Created by Eclipse IDE

Figure 1: Directory Structure Created by Eclipse IDE

Figure 1 list the directory structure created using the eclipse ide.

While we deploy this application on the web server, it loads the default jsp page index.jsp and list the url to load the servlet url “/ListenerExample” as shown into Figure 1 and Figure 2:

Index.jsp page loaded after application deployment

Figure 2: Index.jsp page loaded after application deployment

Figure 2 shows the default loaded pages of the web application that gives a url to re-direct to the servlet as shown into the figure 2:

/ListenerExample servlet loaded

Figure 3: /ListenerExample servlet loaded

Figure 3 loads the servlet class using url /ListenerExample.

Conclusion:

In this article, we learn about the ServletContext and ServletContextListenerobjext and their needs. We also learn about its use using an example defined into this article.



Working in Software Development domain from 7 years now and is well equipped with programming languages like HTML, CSS, Java, PHP, .NET etc.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login