Friday 15 August 2014

ServletContextListener

There are situations like, you have to initialize particular object (Ex: Database connections) before processing any request. In that case ServletContextListener is useful. ContextListener allows you to perform actions after the context is ready, but before any servlets are created.

In order to receive these notification events, the implementation class must be either declared in the deployment descriptor of the web application, annotated with WebListener, or registered via one of the addListener methods defined on ServletContext.

There are 2 ways to register a ServletContext Listener
  1. Using Deployment Descriptor
  2. Using @WebListener Annotation
Main.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="get" action="/servlet/ContextListenerEx">
            <input type="submit">
        </form>
    </body>
</html>

Admin.java
public class Admin {
    String name;
    String description;
    
    Admin(String name, String description){
        this.name = name;
        this.description = description;
    }
    
    String getName(){
        return name;
    }
    
    String getDescription(){
        return description;
    }
}

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

public class InitializeListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        String adm1 = context.getInitParameter("admin1");
        String adm2 = context.getInitParameter("admin2");
        String desc1 = context.getInitParameter("admin1Des");
        String desc2 = context.getInitParameter("admin2Des");
        
        Admin admin1 = new Admin(adm1, desc1);
        Admin admin2 = new Admin(adm2, desc2);
        
        context.setAttribute("admin1", admin1);
        context.setAttribute("admin2", admin2);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
      System.out.println("Context Destroyed");
    }
}

ContextListenerEx.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ContextListenerEx extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        
        try(PrintWriter out = res.getWriter()){
            String header = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> <br />";                     
            String footer = "</h1> </body>" +
                    "</html>";
            ServletContext context = req.getServletContext();
            Admin adm1 = (Admin)context.getAttribute("admin1");
            Admin adm2 = (Admin)context.getAttribute("admin2");
            
            StringBuilder str = new StringBuilder();
            str.append("<br />").append(adm1.getName()).append(":").append(adm1.getDescription());
            str.append("<br />").append(adm2.getName()).append(":").append(adm2.getDescription());
            
            out.println(header);
            out.println(str);
            out.println(footer);
        }
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <listener>
        <description>ServletContextListener</description>
        <listener-class>InitializeListener</listener-class>
    </listener>
    <context-param>
        <param-name>admin1</param-name>
        <param-value>Krishna</param-value>
    </context-param>
    <context-param>
        <param-name>admin2</param-name>
        <param-value>Hari</param-value>
    </context-param>
    <context-param>
        <param-name>admin1Des</param-name>
        <param-value>Primary Admin</param-value>
    </context-param>
    <context-param>
        <param-name>admin2Des</param-name>
        <param-value>Secondary Admin</param-value>
    </context-param>
    <servlet>
        <servlet-name>ContextListenerEx</servlet-name>
        <servlet-class>ContextListenerEx</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ContextListenerEx</servlet-name>
        <url-pattern>/ContextListenerEx</url-pattern>
    </servlet-mapping>
</web-app>

Output





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment