5 listeners, servlet

57
Listeners

Upload: suresh1130

Post on 13-Nov-2014

141 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 5  Listeners, servlet

Listeners

Page 2: 5  Listeners, servlet

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

Page 3: 5  Listeners, servlet

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

Page 4: 5  Listeners, servlet

Know

• What Listeners are• Types of Listeners

Page 5: 5  Listeners, servlet

Be able to

• Use Listeners

Page 6: 5  Listeners, servlet

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.

Page 7: 5  Listeners, servlet

Types of Listeners

• For every scope , there is a relevant Listener

Request ListenerContext ListenerSession Listener

Page 8: 5  Listeners, servlet

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

Page 9: 5  Listeners, servlet

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.

Page 10: 5  Listeners, servlet

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).

Page 11: 5  Listeners, servlet

Hierarchy of ServletRequestEvent and ServletRequestAttributeEvent

EventObject

Object getSource()

ServletRequestEvent

ServletContext getServletContext()ServletRequest getServletRequest()

ServletRequestAttributeEvent

String getName()Object getValue()

javax.servlet

java.util

Page 12: 5  Listeners, servlet

Example

• Calculating the time a user spent in a web site.

Page 13: 5  Listeners, servlet

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){

Page 14: 5  Listeners, servlet

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); }

Page 15: 5  Listeners, servlet

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"); } }

Page 16: 5  Listeners, servlet

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.

Page 17: 5  Listeners, servlet

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.

Page 18: 5  Listeners, servlet

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>"); } }

Page 19: 5  Listeners, servlet

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.

Page 20: 5  Listeners, servlet

"+(Integer)sess.getAttribute("time")+"<h2> </b>"); out.println("<br><a

href='first.do'>back</a></body></html>"); } }

Page 21: 5  Listeners, servlet

<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

Page 22: 5  Listeners, servlet

<listener> <listener-class> TimeCounter </listener-class> </listener>

</web-app>

Page 23: 5  Listeners, servlet

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

Page 24: 5  Listeners, servlet

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.

Page 25: 5  Listeners, servlet

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).

Page 26: 5  Listeners, servlet

Hierarchy of ServletContextEvent and ServletContextAttributeEvent

EventObject

Object getSource()

ServletContextEvent

ServletContext getServletContext()

ServletContextAttributeEvent

String getName()Object getValue()

javax.servlet

java.util

Page 27: 5  Listeners, servlet

Example

• Getting the JNDI for datasource from DD and storing the DataSource object in the application context .

Page 28: 5  Listeners, servlet

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.

Page 29: 5  Listeners, servlet

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.

Page 30: 5  Listeners, servlet

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"); } }

Page 31: 5  Listeners, servlet

<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

Page 32: 5  Listeners, servlet

<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>

Page 33: 5  Listeners, servlet

<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>

Page 34: 5  Listeners, servlet

// 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{

Page 35: 5  Listeners, servlet

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>").

Page 36: 5  Listeners, servlet

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);} } } }

Page 37: 5  Listeners, servlet

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

Page 38: 5  Listeners, servlet

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)

Page 39: 5  Listeners, servlet

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).

Page 40: 5  Listeners, servlet

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.

Page 41: 5  Listeners, servlet

On Line Shopping Center.

Page 42: 5  Listeners, servlet

Discount is only valid for festival season and when total is greater than Rs 5000.

Page 43: 5  Listeners, servlet

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.

Page 44: 5  Listeners, servlet

ses.setAttribute("DiscountAmt",new Double(20)) ; }

public void attributeRemoved(HttpSessionBindingEventevent){ }

Page 45: 5  Listeners, servlet

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)) ; } }

Page 46: 5  Listeners, servlet

// 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 .

Page 47: 5  Listeners, servlet

ses.setAttribute("Total",new Double(totalamt));

Double

dis=(Double)ses.getAttribute("DiscountAmt");

// Check whether dis==null and calculate

the net payment. }

Page 48: 5  Listeners, servlet

<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>

Page 49: 5  Listeners, servlet

<listener> <listener-class> DiscountCheck </listener-class> </listener>

</web-app>

This Discount part can easily takenaway after the festival without altering

other codes

Page 50: 5  Listeners, servlet

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.

Page 51: 5  Listeners, servlet

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.

Page 52: 5  Listeners, servlet

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.

Page 53: 5  Listeners, servlet

Heirarchy of HttpSessionEvent and HttpSessionBinding Event

EventObject

Object getSource()

HttpSessionEvent

HttpSessionBindingEvent javax.servlet.http

java.util

Page 54: 5  Listeners, servlet

HttpSessionBindingListener And

HttpSessionActivationListener are not declared in Deployment Descriptor!!

Page 55: 5  Listeners, servlet

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.

Page 56: 5  Listeners, servlet

web.xml<web-app . . .>. . .

<listener><listener-class>

com.listen.RequestListener</listener-class>

</listener><listener>

<listener-class>com.listen.SessionListener

</listener-class></listener>

. . .</web-app>

Page 57: 5  Listeners, servlet