Вы находитесь на странице: 1из 22

Listeners

HttpSessionEvent and HttpSessionListener

Listenerlogin.html
<form action="ListenerFirst"> Name:<input type="text" name="username"><br> Password:<input type="password" name="userpass"><br> <input type="submit" value="login" /> </form>

import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class ListenerCountUser implements HttpSessionListener{ ServletContext ctx=null; static int total=0,current=0; public void sessionCreated(HttpSessionEvent e) { total++; current++; ctx=e.getSession().getServletContext(); ctx.setAttribute("totalusers", total); ctx.setAttribute("currentusers", current); } public void sessionDestroyed(HttpSessionEvent e) { current--; ctx.setAttribute("currentusers",current); } }

import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ListenerFirst extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("username"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); ServletContext ctx=getServletContext(); int t=(Integer)ctx.getAttribute("totalusers"); int c=(Integer)ctx.getAttribute("currentusers"); out.print("<br>total users= "+t); out.print("<br>current users= "+c); out.print("<br><a href='ListenerLogout'>logout</a>");

out.close(); }
}

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; import javax.servlet.http.HttpSession; public class ListenerLogout extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); session.invalidate(); out.print("You are successfully logged out"); out.close(); } }

web.xml <listener> <listener-class>ListenerCountUser</listener-class> </listener> <servlet> <servlet-name>ListenerFirst</servlet-name> <servlet-class>ListenerFirst</servlet-class> </servlet> <servlet> <servlet-name>ListenerLogout</servlet-name> <servlet-class>ListenerLogout</servlet-class> </servlet> <servlet-mapping> <servlet-name>ListenerFirst</servlet-name> <url-pattern>/ListenerFirst</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ListenerLogout</servlet-name> <url-pattern>/ListenerLogout</url-pattern> </servlet-mapping>

Listeners
The servlet specification includes the capability to track key events in your Web applications through event listeners. This functionality allows more efficient resource management and automated processing based on event status Use Web Application events to: Manage database connections when a Web Application is deployed or shuts down Create counters Monitor the state of HTTP sessions and their attributes

There are two levels of servlet events:


1. Servlet context-level (application-level) event This event involves resources or state held at the level of the application servlet context object. 2. Session-level event This event involves resources or state associated with the series of requests from a single user session; that is, associated with the HTTP session object. Each of these two levels has two event categories: Lifecycle changes created , destroyed Attribute changes add, remove, replace You can create one or more event listener classes for each of the four event categories. A single listener class can monitor multiple event categories.

Listeners
Application events provide notifications of a change in state of the servlet context (each Web Application uses its own servlet context) or of an HTTP session object .You write event listener classes that respond to these changes in state and you configure and deploy Application event and listener classes in a Web Application. For servlet context events, the event listener classes can receive notification when the Web Application is deployed or is being undeployed (or when WebLogic Server shuts down), and when attributes are added, removed, or replaced. For HTTP session events, the event listener classes can receive notification when an HTTP session is activated or is about to be passivated, and when an HTTPsession attribute is added, removed, or replaced.

Servlet Context Events


The following table lists the types of Servlet context events, the interface your event listener class must implement to respond to the event, and the methods invoked when the event occurs.
Event Servlet context is created Servlet context is destroyed An attribute is added An attribute is removed An attribute is replaced Interface Javax.servlet.ServletContextListener Javax.servlet.ServletContextListener Javax.servlet.ServletContextAttributeListener Javax.servlet.ServletContextAttributeListener Javax.servlet.ServletContextAttributeListener

SessionEvents
The following table lists the types of HTTP session events, the interface your event listener class must implement to respond to the event, and the methods invoked when the event occurs.
Event Session is created Session is destroyed An attribute is added An attribute is removed An attribute is replaced Interface Javax.servlet.SessionListener Javax.servlet. Session Listener Javax.servlet. SessionAttributeListener Javax.servlet. Session AttributeListener Javax.servlet. Session AttributeListener

How to configure Listeners


To configure an event listener: In web.xml add an event declaration using the <listener> element. The event declaration defines the listener class that is invoked when the event occurs. The <listener> element must directly follow the <filter> and <filtermapping>elements and directly precede the <servlet> element. Can specify more than one listener class for each type of event. For Example: <listener> <listener-class>myApp.myContextListenerClass</listener-class> </listener> <listener> <listener-class>myApp.mySessionAttributeListenerClass</listener-class> </listener>

To write a listener class: 1 . Create a new class that implements the appropriate interface for the type of event your class responds to. 2. Create a public constructor that takes no arguments. 3. Implement the required methods of the interface. The following useful classes are passed into the listener methods in a listener class:
javax.servlet.http.HttpSessionEvent provides access to the HTTP session object javax.servlet.ServletContextEvent provides access to the servlet context object. javax.servlet.ServletContextAttributeEvent provides access to servlet context and its attributes javax.servlet.http.HttpSessionBindingEvent provides access to an HTTP session and its attribute

Template for ServletContext listener


Servlet Context Listener Example package myApp; import javax.servlet.*;

public final class myContextListenerClass implements ServletContextListener{ public void contextInitialized(ServletContextEvent event) {

System.out.println(initialized before server starts completely");


/* This method is called when the servlet context is initialized(when the WebApplication is deployed).We can initialize servlet context related data here. */ } public void contextDestroyed(ServletContextEvent event) { /* This method is invoked when the Servlet Context is undeployed or when Server shuts down. */ } }

Template for SessionContextlistener


Session Listener Example package myApp; import javax.servlet.*; public final class mySessionListenerClass implements SessionListener{ public void sessionCreated(SessionEvent event) { /* This method is called when the session is created*/ } public void sessionDestroyed(SessionEvent event) { /* This method is invoked when the session is destroyed. */ }
}

Template for SessionAttributelistener


package myApp; import javax.servlet.*; public final class mySessionAttributeListenerClass implementsHttpSessionAttributeListener{ public void attributeAdded(HttpSessionBindingEvent sbe) {/* This method is called when an attributeis added to a session. */ } public void attributeRemoved(HttpSessionBindingEvent sbe) { /* This method is called when an attributeis removed from a session. */ } public void attributeReplaced(HttpSessionBindingEvent sbe) { /* This method is invoked when an attibuteis replaced in a session. */ } }