August 28, 2011

JSP Life-cycle methods

The 3 life-cycle methods of a JSP are,
  • jspInit()
  • _jspService()
  • jspDestroy()
The jspInit() executes when the object of the JSP servlet class is created by the Container, right after the constructor finishes executing.

The jspDestroy() executes when the JSP Servlet object is removed or taken down by the Container.

The _jspService() method executes everytime a request is sent to the JSP. Code in scriptlets and expressions lands in the _jspService() method.

Code in the JSP declaration element lands outside the _jspService() method but inside the JSP Servlet class, after translation.

The jspInit() and jspDestroy() methods execute only once in the life of the JSP Servlet object. The _jspService() executes n times, where n = number of requests sent to the JSP

Create a JSP - JspLifecycleDemo.jsp - in the WebContent folder of the web application,

<html>
<head>
<title>JSP lifecycle methods</title>
</head>
<body>
<%!
public void jspInit() {
   System.out.println("JSP initialized"); 
}

public void jspDestroy() {
   System.out.println("JSP Destroyed"); 
}
%>

<%= "Inside _jspService() method"  %>

</body>
</html>

Test the code with the following URL in the browser,

http://localhost:8080/WebAppName/JspLifecycleDemo.jsp

Check the server/console log for the output of the jspInit() method. Stopping the server will display the output of the jspDestroy() on the server/console log.

JSP Implicit Objects Demo

The 9 JSP implicit objects are,
  • request (HttpServletRequest)
  • response (HttpServletResponse)
  • out (JspWriter)
  • session (HttpSession)
  • config (ServletConfig)
  • application (ServletContext)
  • page (Object)
  • pageContext (PageContext)
  • exception (Throwable)
Create a JSP - ImplicitObjectsDemo.jsp - in the WebContent folder of the web application,

<html>
<head>
   <title>Implicit Objects Demo</title>
</head>
<body>
<%= "test = " + request.getParameter("test") %>

<% response.setHeader("MyHeader", "MyValue"); %>
<br/><br/>
<%= "Session Id= " + session.getId() %>
<br/><br/>
<%= "Servlet API version supported (through ServletContext): " + application.getMinorVersion() + "." + application.getMinorVersion() %>
<br/><br/>
<%= "The JSP Servlet name (through ServletConfi) " + config.getServletName() %>
<br/><br/>
<%= "JSP Servlet class name (through page) is " + page.getClass().getName() %>

</body>
</html>

Test the code with the following URL in the browser,

http://localhost:8080/WebAppName/ImplicitObjectsDemo.jsp?test=abcd

HttpSessionBindingListener Event Handler Implementation

The HttpSessionBindingListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on an object that is bound to the session object as an attribute, namely, the binding and un-binding of the attribute object to the session.

The HttpSessionBindingEvent object that is passed as an argument to the listener methods provides a handle to the HttpSession object as well as access to the name and value object of the attribute.

1) Create an attribute class that implements the HttpSessionBindingListener interface methods, valueBound() and valueUnbound()

package info.icontraining.servlets;

import javax.servlet.http.*;

public class MyAttribute implements HttpSessionBindingListener {

   String id;
 
   public MyAttribute(String id) {
      this.id = id;
   }
 
   public String getId() {
      return this.id;
   }
 
   public void valueBound(HttpSessionBindingEvent hsbe) {
      HttpSession session = hsbe.getSession();
      System.out.println("Attribute added to session. Id = " + ((MyAttribute)hsbe.getValue()).getId());
   }

   public void valueUnbound(HttpSessionBindingEvent hsbe) {
      System.out.println("Attribute removed from session. Id = " + ((MyAttribute)hsbe.getValue()).getId());
   }
}

2) For the HttpSessionBindingListener class, configuration in the web.xml with the <listener> element is not required.

3) Create a servlet class that adds and removes the attribute to and from the session,

package info.icontraining.servlets;

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

public class SessionServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();
        
        session.setAttribute("newAttr", new MyAttribute("20"));
        session.removeAttribute("newAttr");
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>sessionServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>sessionServlet</servlet-name>
   <url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/sessionServlet

ServletRequestAttributeListener Event Handler Implementation

The ServletRequestAttributeListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletRequest object, namely, the addition, removal and replacement of attributes on the request object.

The ServletRequestAttributeEvent Event object that is passed as an argument to the listener methods provides a handle to the ServletRequest object and the name and value object of the attribute.

1) Create a class that implements the ServletRequestAttributeListener interface methods, attributeAdded(), attributeRemoved() and attributeReplaced()

package info.icontraining.servlets.listeners;

import javax.servlet.*;
import javax.servlet.http.*;

public class MyRequestAttributeListener implements ServletRequestAttributeListener {

   public void attributeAdded(ServletRequestAttributeEvent srae) {
      System.out.println("New request attribute added");
      HttpServletRequest request = (HttpServletRequest) srae.getServletRequest();
      System.out.println("Name of Attribute added: " + srae.getName());
      System.out.println("Value of Attribute added: " + srae.getValue());
   }

   public void attributeRemoved(ServletRequestAttributeEvent srae) {
      System.out.println("Request attribute Removed");
      System.out.println("Name of Attribute removed: " + srae.getName());
      System.out.println("Value of Attribute removed: " + srae.getValue());
   }

   public void attributeReplaced(ServletRequestAttributeEvent srae) {
      System.out.println("Request attribute Replaced");
      System.out.println("Name of Attribute replaced: " + srae.getName());
      System.out.println("Value of Attribute replaced: " + srae.getValue());
   }
}

2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyRequestAttributeListener
   </listener-class>
</listener>

3) Create a servlet class that handles a request,

package info.icontraining.servlets;

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

public class RequestListenerServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      request.setAttribute("attr1", "value1");
      request.setAttribute("attr1", "value2");
      request.removeAttribute("attr1");
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>requestListenerServlet </servlet-name>
   <servlet-class>info.icontraining.servlets.RequestListenerServlet </servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>requestListenerServlet </servlet-name>
   <url-pattern>/RequestListenerServlet </url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/requestListenerServlet

ServletRequestListener Event Handler Implementation

The ServletRequestListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletRequest object, namely, the request object creation and destruction.

TheServletRequest Event object that is passed as an argument to the 2 listener methods provides a handle to the ServletRequest object.

1) Create a class that implements the ServletRequestListener interface methods, requestInitialized() and requestDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

public class MyServletRequestListener implements ServletRequestListener{

   public void requestDestroyed(ServletRequestEvent sre) {
      System.out.println("Request serviced & object destroyed by container");
   }

   public void requestInitialized(ServletRequestEvent sre) {
      System.out.println("New Request received and object created");
      HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
      // do something when a new request arrives
   }
}
2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyServletRequestListener
   </listener-class>
</listener>

3) Create a servlet class that handles a request,

package info.icontraining.servlets;

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

public class RequestListenerServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      request.setAttribute("attr1", "value1");
      request.setAttribute("attr1", "value2");
      request.removeAttribute("attr1");
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>requestListenerServlet </servlet-name>
   <servlet-class>info.icontraining.servlets.RequestListenerServlet </servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>requestListenerServlet </servlet-name>
   <url-pattern>/RequestListenerServlet </url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/requestListenerServlet

HttpSessionAttributeListener Event Handler Implementation

The HttpSessionAttributeListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the HttpSession object, namely, the addition, removed and replacement of attributes on the HttpSession object.

The HttpSessionBindingEvent object that is passed as an argument to the 2 listener methods provides a handle to the HttpSession object as well as access to the name and value object of the attribute.

1) Create a class that implements the HttpSessionAttributeListener interface methods, attributeAdded(), attributeRemoved() and attributeReplaced()

package info.icontraining.servlets.listeners;

import javax.servlet.http.*;

public class MySessionAttrListener implements HttpSessionAttributeListener {

   public void attributeAdded(HttpSessionBindingEvent hsbe) {
      System.out.println("New Session attribute added");
      HttpSession session = hsbe.getSession();
      System.out.println("Name of Attribute added: " + hsbe.getName());
      System.out.println("Value of Attribute added: " + hsbe.getValue());
   }

   public void attributeRemoved(HttpSessionBindingEvent hsbe) {
      System.out.println("Session attribute Removed");
      System.out.println("Name of Attribute removed: " + hsbe.getName());
      System.out.println("Value of Attribute removed: " + hsbe.getValue());
   }

   public void attributeReplaced(HttpSessionBindingEvent hsbe) {
      System.out.println("Session attribute replaced");
      System.out.println("Name of Attribute replaced: " + hsbe.getName());
      System.out.println("Value of Attribute replaced: " + hsbe.getValue());
   } 
}
2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MySessionAttrListener
   </listener-class>
</listener>

3) Create a servlet class that starts a session and adds, replaces and removes a session attribute,

package info.icontraining.servlets;

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

public class SessionServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)  
   throws IOException {

      HttpSession session = request.getSession();
      session.setAttribute("attr1", "value1");
      session.setAttribute("attr1", "value2");
      session.removeAttribute("attr1");
      session.invalidate();
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>sessionServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>sessionServlet</servlet-name>
   <url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/sessionServlet

HttpSessionListener Event Handler Implementation

The HttpSessionListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the HttpSession object, namely, the HttpSession object creation and destruction.

The HttpSessionEvent object that is passed as an argument to the 2 listener methods provides a handle to the HttpSession object in order to set any attributes.

1) Create a class that implements the HttpSessionListener interface methods, sessionCreated() and sessionDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.http.*;

public class MySessionListener implements HttpSessionListener {

   public void sessionCreated(HttpSessionEvent se) {
      System.out.println("Created new session with client");
      HttpSession session = se.getSession();
      System.out.println("Printing Session Id: " + session.getId());
   }

   public void sessionDestroyed(HttpSessionEvent se) {
      System.out.println("Session "+ se.getSession().getId() +" ended");
   }
}

2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MySessionListener
   </listener-class>
</listener>

3) Create a servlet class that starts a session

package info.icontraining.servlets;

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

public class SessionServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      HttpSession session = request.getSession();
      session.invalidate();
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>sessionServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>sessionServlet</servlet-name>
   <url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/sessionServlet

ServletContextAttributeListener Event Handler Implementation

The ServletContextAttributeListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletContext object, namely, addition, removal and replacement of attributes on the ServletContext.

The ServletContextAttributeEvent object that is passed as an argument to the 2 listener methods provides a handle to the ServletContext object and the name and value object of the attribute.

1) Create a class that implements the ServletContextAttributeListener interface methods, attributeAdded(), attributeReplaced() and attributeRemoved()

package info.icontraining.servlets.listeners;

import javax.servlet.*;

public class MyContextAttributeListener implements ServletContextAttributeListener {

   public void attributeAdded(ServletContextAttributeEvent scae) {
      System.out.println("New Context attribute added");
      ServletContext sc = scae.getServletContext();
      System.out.println("Name of Attribute added: " + scae.getName());
      System.out.println("Value of Attribute added: " + scae.getValue());
   }

   public void attributeRemoved(ServletContextAttributeEvent scae) {
      System.out.println("Context attribute removed");
      System.out.println("Name of Attribute removed: " + scae.getName());
      System.out.println("Value of Attribute removed: " + scae.getValue());
   }

   public void attributeReplaced(ServletContextAttributeEvent scae) {
      System.out.println("Context attribute replaced");
      System.out.println("Name of Attribute replaced: " + scae.getName());
      System.out.println("Value of Attribute replaced: " + scae.getValue());
   }
}


2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyContextAttributeListener
   </listener-class>
</listener>

3) Create a servlet class that adds, replaces and removes an attribute from the ServletContext

package info.icontraining.servlets;

import java.io.*;

import javax.servlet.ServletContext;
import javax.servlet.http.*;

public class ContextAttribute extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      ServletContext sc = getServletContext();
      sc.setAttribute("attr1", "value1");
      sc.setAttribute("attr1", "value2");
      sc.removeAttribute("attr1");  
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>contextAttribute</servlet-name>
   <servlet-class>info.icontraining.servlets.ContextAttribute</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>contextAttribute</servlet-name>
   <url-pattern>/contextAttribute</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/contextAttribute

ServletContextListener Event Handler Implementation

The ServletContextListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletContext object, namely, the ServletContext object creation/initialization and the ServletContext object destruction.

The ServletContextEvent object that is passed as an argument to the 2 listener methods provides a handle to the ServletContext object in order to set any attributes.

1) Create a class that implements the ServletContextListener interface methods, contextInitialized () and contextDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.*;

public class MyServletContextListener implements ServletContextListener {
   public void contextInitialized(ServletContextEvent sce) {
      System.out.println("Servlet Context created");

      // code to acquire resource, to set as 
      // attr in application scope

      ServletContext sc = sce.getServletContext();
      sc.setAttribute("attr-name", "attr-value");
   }

   public void contextDestroyed(ServletContextEvent sce) {
      // any clean-up code
      System.out.println("Servlet Context destroyed");
   }
}

2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyServletContextListener
   </listener-class>
</listener>

3) Deploy the application to the Application Server/ Web Container and check in the server/console log for the following output,

INFO  [STDOUT] Servlet Context created