5 listeners, servlet
TRANSCRIPT
Listeners
Contents
1 Listeners
2 Types of Listeners
3 Request Listeners
4 Hierarchy of Servlet Request Event and Servlet Request AttributeEvent
5 The Servlet Request Listener Class
6 The Timer Class.
7 The First Servlet Which Is Reading The “time” Attribute.
8 Another Servlet In The Same Application Reading The “time” Attribute.
9 Declaration Of Listeners in DD
10 Context Listeners
Contents
11 Hierarchy of Servlet Context Event and Servlet Context AttributeEvent
12 A Simple Java Code
13 The ServletContextListener implementing class.
14 The web.xml
15 Session Listeners
16 Listener that is calculating the discount.
17 Servlet that generating the bill .
18 Heirarchy of HttpSessionEvent and HttpSessionBinding Event
19 Declaration in Deployment Descriptor
Know
• What Listeners are• Types of Listeners
Be able to
• Use Listeners
Listeners
• Listeners are java files that are invoked by the web container on occurrence of some event.
• They work in much the same way as listeners in the Swing user interface environment.
• For both frameworks (web container and Swing), the listener methods are called in response to the relevant events. For example: for Swing , a mouse movement; for web container, an attribute added.
Types of Listeners
• For every scope , there is a relevant Listener
Request ListenerContext ListenerSession Listener
Request Listeners
Responds to any change to the set of attributes attached to a request object.
ServletRequestAttributeListener
Responds to the life and death of each request.
ServletRequestListener
FunctionListener Interface
A class implementing ServletRequestListener interface has two methods to implement;
• public void requestInitialized(ServletRequestEvent event)-called at the beginning of any request’s scope.
• public void requestDestroyed(ServletRequestEvent event)-called for each request that comes to an end.
A class implementing ServletRequestAttributeListener interface has three methods to implement.
• public void attributeAdded(ServletRequestAttributeEvent event) – called when ever a new attribute is added to any request.
• public void attributeRemoved(ServletRequestAttributeEvent event) – called whenever an attribute is removed from the request.
• public void attributeReplaced(ServletRequestAttributeEvent event) – called whenever a request attribute is replaced (calling setAttribute() for an attribute name already in use by the request).
Hierarchy of ServletRequestEvent and ServletRequestAttributeEvent
EventObject
Object getSource()
ServletRequestEvent
ServletContext getServletContext()ServletRequest getServletRequest()
ServletRequestAttributeEvent
String getName()Object getValue()
javax.servlet
java.util
Example
• Calculating the time a user spent in a web site.
The Servlet Request Listener Class.import javax.servlet.*;import javax.servlet.http.*;
public class TimeCounter implements ServletRequestListener{public void requestInitialized(ServletRequestEvent event) { HttpServletRequest req=(HttpServletRequest)event.getServletRequest();
HttpSession ses=req.getSession(false);if(ses==null){
HttpSession sess=req.getSession();Timer tm=new Timer(); Thread t=new Thread(tm); t.setDaemon(true); t.start(); sess.setAttribute("time",new
Integer(tm.sec)); sess.setAttribute("threadObj",tm); }
else { Timer tt=(Timer)ses.getAttribute("threadObj"); ses.setAttribute("time",new Integer(tt.sec)); System.out.println((Integer)ses.getAttribute("time")); } } public void requestDestroyed(ServletRequestEvent event) { System.out.println("out"); } }
public class Timer implements Runnable { int sec=1; public void run() { try{ while(true) { Thread.sleep(1000); sec++; } }catch(Exception e){System.out.println(e);} } }
The Timer Class.
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { HttpSession sess=req.getSession(); PrintWriter out=res.getWriter(); out.println("<html><body><h1>FirstServlet</h1>");
The First Servlet Which Is Reading The “time” Attribute.
out.println("<b><h2>You have spent "+(Integer)sess.getAttribute("time")+" sec</h2> </b>");
out.println("<br><a href='second.do'>next</a><br>");
out.println("<br><a
href='index.html'>home</a></body></html>"); } }
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { HttpSession sess=req.getSession(); PrintWriter out=res.getWriter(); out.println("<html><body><h1>SecondServlet</h1>"); out.println("<b><h2>You have spent
Another Servlet In The Same Application Reading The “time” Attribute.
"+(Integer)sess.getAttribute("time")+"<h2> </b>"); out.println("<br><a
href='first.do'>back</a></body></html>"); } }
<web-app> <display-name>Servlet Request Listener Test</display-name> <servlet> //Declare the servlets </servlet>
<servlet-mapping> // Give the urls </servlet-mapping>
Declaration Of Listeners in DD
<listener> <listener-class> TimeCounter </listener-class> </listener>
</web-app>
Context Listeners
Responds to any change to the set of attributes attached to the context object.
ServletContextAttributeListener
Responds to the life and death of the context for a web application.
ServletContextListener
FunctionListener Interface
A class implementing ServletContextListener interface has two methods to implement;
• public void contextInitialized(ServletContextEvent event)-called at the beginning of web application.
• public void contextDestroyed(ServletContextEvent event)-called when the web application is taken out of service.
A class implementing ServletContextAttributeListener interface has three methods to implement.
• public void attributeAdded(ServletContextAttributeEvent event) – called when ever a new attribute is added to the servlet context.
• public void attributeRemoved(ServletContextAttributeEvent event) – called whenever an attribute is removed from the servlet context.
• public void attributeReplaced(ServletContextAttributeEvent event) – called whenever a context attribute is replaced (calling setAttribute() for an attribute name already in use by the servlet context).
Hierarchy of ServletContextEvent and ServletContextAttributeEvent
EventObject
Object getSource()
ServletContextEvent
ServletContext getServletContext()
ServletContextAttributeEvent
String getName()Object getValue()
javax.servlet
java.util
Example
• Getting the JNDI for datasource from DD and storing the DataSource object in the application context .
public class Conn { String driver; String url; String username; String password;
public Conn(){}
public Conn(String d,String u,String user,String pass) { driver=d; url=u; username=user; password=pass; } }
A Simple Java Code
Before the Servlet being loaded the ContextListener class create the Conn object
by reading the values from the DD. And set it to the ServletContext.
We can change all the database parameters from the DD only.
import javax.servlet.*;public class CreateConn implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { ServletContext ctx=event.getServletContext(); String dname=ctx.getInitParameter("driver"); String
The ServletContextListener implementing class.
urladd=ctx.getInitParameter("url"); String uname=ctx.getInitParameter("username"); String pass=ctx.getInitParameter("password"); Conn con=newConn(dname,urladd,uname,pass); ctx.setAttribute("ConnectionDesc",con); System.out.println("Context initialized"); } public void contextDestroyed(ServletContextEvent
event) { System.out.println("Context destroyed"); } }
<web-app> <display-name>Servlet Context Listener Test</display-name> // Write all the Servlet Related tags
<listener> <listener-class> CreateConn </listener-class> </listener>
The web.xml
<context-param> <param-name>driver</param-name> <param-value>oracle.jdbc.OracleDriver</paramvalue></context-param>
<context-param> <param-name>url</param-name> <paramvalue>jdbc:oracle:thin:@scicom6:1521:xe</param-
value></context-param>
<context-param> <param-name>username</param-name> <param-value>SYSTEM</param-value></context-param>
<context-param> <param-name>password</param-name> <param-value>scicom</param-value></context-param>
</web-app>
// Write the imports statements.
public class ShowData extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { PrintWriter out=res.getWriter(); Conn cn=(Conn)getServletContext().getAttribute("ConnectionDesc"); if(cn==null) { out.println("<html><body><b> Connection not possible</b>"); } else { try{
Class.forName(cn.driver); Connectioncon=DriverManager.getConnection(cn.url,cn.userna
me,cn.password); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select *
from student"); out.println("<br><center><b>Student
Details</b><br><table border=1>").
while(rs.next()) { out.println("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td>"); } out.println("</table></center>"); out.println("</body></html>"); con.close(); }catch(Exception e){System.out.println(e);} } } }
Session Listeners
Responds when a value object is transported across JVM’s (distributed environment)
HttpSessionActivationListener
Responds when a value object is used as a session attribute
HttpSessionBindingListener
Responds to any change to the set of attributes attached to the session object
HttpSessionAttributeListener
Responds to the life and death of the session
HttpSessionListener
FunctionListener Interface
A class implementing HttpSessionListener interface has two methods to implement;
• public void sessionCreated(HttpSessionEvent event)-called when a new session is created.
• public void sessionDestroyed(HttpSessionEvent event)-called at the moment a session is about to be invalidated (but before the session becomes invalid and unusable)
A class implementing HttpSessionAttributeListener interface has three methods to implement.
• public void attributeAdded(HttpSessionBindingEvent event) – called when ever a new attribute is added to any session
• public void attributeRemoved(HttpSessionBindingEvent event) – called whenever an attribute is removed from any session.
• public void attributeReplaced(HttpSessionBindingEvent event) – called whenever an attribute is replaced (calling setAttribute() for an attribute name already in use on the called session).
Example
• Write an application that sells groceries online. Since this is a festival season, the shop want to give discount of 10% on purchase of more than Rs.1000.
• Write the discount part of the code as an independent component such that it can be plucked and attached from the application anytime.
On Line Shopping Center.
Discount is only valid for festival season and when total is greater than Rs 5000.
import javax.servlet.*;import javax.servlet.http.*;
public class DiscountCheck implements HttpSessionAttributeListener { public void attributeAdded(HttpSessionBindingEvent event) { HttpSession ses=event.getSession(); System.out.println("added"); ses.removeAttribute("DiscountAmt"); Double tot=(Double)ses.getAttribute("Total"); if(tot.doubleValue()>5000)
Listener that is calculating the discount.
ses.setAttribute("DiscountAmt",new Double(20)) ; }
public void attributeRemoved(HttpSessionBindingEventevent){ }
public void attributeReplaced(HttpSessionBindingEvent event) { HttpSession ses=event.getSession(); ses.removeAttribute("DiscountAmt"); System.out.println("replaced"); Double tot=(Double)ses.getAttribute("Total"); if(tot.doubleValue()>5000) ses.setAttribute("DiscountAmt",new Double(20)) ; } }
// import statementspublic class GenerateBill extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { PrintWriter out=res.getWriter(); String []item=req.getParameterValues("chk1"); // Create the season and read the DiscountAmt Attribute added by the attributeAdded() method. ........................................................ .........................................................
Servlet that generating the bill .
ses.setAttribute("Total",new Double(totalamt));
Double
dis=(Double)ses.getAttribute("DiscountAmt");
// Check whether dis==null and calculate
the net payment. }
<web-app> <display-name>Http Listener Test</display-name>
<servlet> <servlet-name>GenerateBill</servlet-name> <servlet-class>GenerateBill</servlet-class> </servlet>
<servlet-mapping> <servlet-name>GenerateBill</servlet-name> <url-pattern>/payment.do</url-pattern> </servlet-mapping>
<listener> <listener-class> DiscountCheck </listener-class> </listener>
</web-app>
This Discount part can easily takenaway after the festival without altering
other codes
A class implementing HttpSessionBindingListener interface has two methods to implement.
• public void valueBound(HttpSessionBindingEvent event) – called whenever the object implementing the interface is the value object set as attribute value to the session.
• public void valueUnbound(HttpSessionBindingEvent event) – called whenever the object implementing the interface is the value object removed from the session.
Example• Library application- user browses the library
books and selects the book he want to borrow and adds it to the cart. On adding a library book object into cart(session) it is marked as unavailable in the database in the valueBound(). If it is taken out of the cart then it is marked available.
A class implementing HttpSessionActivationListener interface has two methods to implement.
• public void sessionWillPassivate(HttpSessionEventevent) – called just before a session is serialized to be cloned to another JVM.
• public void sessionDidActivate(HttpSessionEvent event) – called just after a cloned session is deserialized in a target JVM.
Heirarchy of HttpSessionEvent and HttpSessionBinding Event
EventObject
Object getSource()
HttpSessionEvent
HttpSessionBindingEvent javax.servlet.http
java.util
HttpSessionBindingListener And
HttpSessionActivationListener are not declared in Deployment Descriptor!!
Declaration in Deployment Descriptor
• In the DD we need to place a <listener> element whose sub-element is <listener-class>
• The value held in <listener-class> element is fully qualified class name of a listener class.
• For each listener class we need a separate <listener> element.
• Based on the occurrence of event, relevant listener is invoked by the container.
web.xml<web-app . . .>. . .
<listener><listener-class>
com.listen.RequestListener</listener-class>
</listener><listener>
<listener-class>com.listen.SessionListener
</listener-class></listener>
. . .</web-app>