Friday, May 14, 2010

ServletContextListener Example

Context parameters can’t be anything except Strings. So if we want to run some such as database connection before running the rest of application, then the scope of “listeners” come into picture.

If we wants to listen for a context initialization event, so that we can get the context init parameters and run some code before the rest of the application can service a client. In this case we need a listener named “ServletContextListener” 

ServletContextListener Class Structure 

We can make a separate class, not a servlet or JSP, that can listen for the two key events in a ServletContext’s life— initialization (creation) and destruction. That separate class implements javax.servlet.ServletContextListener.  

We need a separate object that can: 

Get notified when the context is initialized (app is being deployed). 
  • Get the context init parameters from the ServletContext. 
  • Use the init parameter lookup name to make a database connection. 
  • Store the database connection as an attribute, so that all parts of the web app can access it.  
Get notified when the context is destroyed (the app is undeployed or goes down). 
  •  Close the database connection.
 ServletContextListener Example:-

STEP1: Create a “dynamic web” project named “ListenerSample”. 

STEP 2: Create a new package named” com.examp” under Src or Source Folder.

STEP 3: ServletContextListener :-Create a new java class named “MyServletContextListener” under Src folder. This class implements ServletContextListener, gets the context init parameters, creates the DBconnection object and sets that object as context attribute.

package com.examp;

import javax.servlet.*;
public class MyServletContextListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent event) {
//code to initialize the database connectionand store it as a context attribute 
ServletContext sc = event.getServletContext();
 String Dbname = sc.getInitParameter("DbName");
 DBconnection d = new DBconnection( Dbname);
 sc.setAttribute("Database", d);
 }

 public void contextDestroyed(ServletContextEvent event) {
// close db connection
 }
 }

 STEP 4: Attribute class: Create a new java class named “DBconnection”. This class job is to be the attribute value that the ServletContextListener instantiates and sets in the ServletContext, for the servlet to retrieve.

package com.examp;

public class DBconnection {
private String DbName;
public DBconnection(String DbName) {
 this.DbName = DbName;
 }
 public String connection() {
 //write code for DB connection here
 this.DbName=DbName.concat("is connected");
 return DbName;
 }
 }

STEP 5: Servlet Progarm :-Create new Java program namer "ServletController" under Src folder.

package com.examp;

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 ServletController extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("test context attributes set by listener
"); out.println("
");

DBconnection Db = (DBconnection) getServletContext().getAttribute("Database");
out.println("Database is: " + Db.connection());
}

STEP 6: Include below code in a Xml file “web.xml” under WEB-INF folder:

< web-app > 
< context-param  > 
< param-name >DbName< /param-name > 
< param-value >MyDatabase< /param-value > 
< /context-param > 
< listener > 
< listener-class > com.examp.MyServletContextListener< /listener-class >
 < /listener >
 < /web-app >

STEP 7: Export the project” ListenerSample” into a war file named ” ListenerSample” and place it in the deploy folder of JBOSS server.

STEP 8:To see the output use this url ” http://localhost:8080/ ListenerSample/Hello” ,where ListenerSample is the .war file name and Hello is specified in the < url-pattern >of web.xmlfile.

 STEP 9: Output :-

 Test context attributes set by listener
 Database is: MyDatabaseis connected

No comments:

Post a Comment