Use of listeners in JSP __js

Source: Internet
Author: User
Tags sessions static class
This content is a servlet listener that adds an event-handling mechanism to the Web application to better monitor and control state changes in the Web application, thereby invoking the appropriate handlers in the background.  

Listener object

Listener interface

Listening event

Serv Letrequest

Servletrequestlistener

servletrequestevent

Servletrequestattributelistener

Servletrequestattributeevent

HttpSession

Httpsessionlistener

Httpsessionevent

Httpsessionactivationlistener

Httpsessionattributelistener

td>

Httpsessionbindingevent

Httpsessionbindinglistener

ServletContext

Servletcontextlistener

Servletcontextevent

td>

Servletcontextattributelistener

Servletcontextattributeevent

L can listen for HTTP session activity, property settings in HTTP sessions, or monitor the active, passivate, and so on of HTTP sessions. The listener needs to use multiple interface classes as follows: Øhttpsessionlistenerøhttpsessionactivationlistenerøhttpsessionattributelistener Øhttpsessionbindinglistener Lhttpsessionlistener: Monitor the operation of the HttpSession. Lhttpsessionactivationlistener: Listens for HTTP session active, passivate. Use this interface to persist data that is not serialized between JVMs, or to perform additional operations on serialized objects before and after the session is moved. Lhttpsessionattributelistener: Listens for the operation of properties in HttpSession. Lhttpsessionbindinglistener: This interface is used to listen for the binding information of objects in an HTTP session.

Listener interface

Event class

Httpsessionlistener

Httpsessionevent

Httpsessionactivationlistener

Httpsessionattributelistener

Httpsessionbindingevent

Httpsessionbindinglistener

Lhttpsessionattributelistener interface methods are: øattributeadded (httpsessionbindingevent se): This method is called when an attribute is added to the session; øattributeremoved (httpsessionbindingevent se): This method is called when a property is deleted in session; Øattributereplaced (httpsessionbindingevent SE): This method is called when the session property is reset.
Lhttpsessionbindingevent method: Øhttpsession getsession (): Can get the Session object Øjava.lang.string GetName: return session increase, Delete or replace the property name Øjava.lang.object getValue (): Returns the value of a property that is added, deleted, or replaced by the session
Lhttpsessionlistener interface methods are: øsessioncreated (httpsessionevent E): When a session is created, the method is called øsessiondestroyed ( Httpsessionevent e): When a session is destroyed, the method is called
Lapplication is an example of ServletContext. The Getservletcontext () method is invoked in Lservlet to get an instance of ServletContext. L A application-scoped object is created when the container is started. The lapplication parameter can be set by the <context-param> element. Set as follows:

<context-param>

<param-name>Name</param-name>

<param-value>Jack</param-value>

</context-param> l A application-scoped object is created when the container is started, and can be obtained by using the following method.

String name = (string) application.getinitparameter ("name");

${initpara.name}

String name = (string) servletcontext.getinitparameter ("name");


L used to listen for Web application startup and destruction events, the listener class needs to implement the Javax.servlet.ServletContextListener interface Lservletcontextlistener is a ServletContext listener, When ServletContext changes, the main method that triggers the listener Lservletcontextlistener interface: øvoid contextinitialized (Servletcontextevent SCE) : Notifies the object being accepted that the application has been loaded and initialized øvoid contextdestroyed (servletcontextevent SCE): Notifies the object being accepted that the application has been destroyed The main method of an event class Lservletcontextevent Lservletcontextlistener interface: Øservletcontext Getservletcontext () Used to get the current ServletContext object Lservletcontextattributelistener: An event that listens for changes to Web application properties, including: Adding properties, deleting attributes, modifying properties, The listener class needs to implement the Javax.servlet.ServletContextAttributeListener interface   Lservletcontextattributelistener interface main methods: øvoidattributeadded (servletcontextattributeevent scae): If an object joins the application range, notify the object being listened to. Øvoidattributeremoved (servletcontextattributeevent scae): If an object is removed from the application range, notify the object being listened to. øvoidattributereplaced (servletcontextattributeevent scae): Notifies an object that is being listened to when an object replaces another object in the application range   Methods in the Lservletcontextattributeevent class: Øjava.lang.string getName (): Returns the name of the property Øjava.lang.object GetValue (): Returns the value of the property  
Lservletrequest monitoring is a new technology added to the Servlet2.4 specification. You can listen for requests from clients. The following two interface classes are used: Øservletrequestlistener interface: An event that listens for client request initialization and destruction and requires implementation of Javax.servlet.ServletRequestListener interface Øservletrequestattributelistener: An event that listens for changes to Web application properties, including: Adding properties, deleting attributes, modifying properties, Listener class needs to implement Javax.servlet.ServletRequestAttributeListener interface
The Lservletrequestlistener interface has two methods: Ørequestinitialized (servletrequestevent): Notifies the current object that the request has been loaded and initialized ørequestdestroyed ( Servletrequestevent): Notifies the current object that the request has been eliminated. Methods in the Lservletrequestevent class: Øservletrequest getservletrequest (): Get ServletRequest object; øservletcontext Getservletcontext (): Gets the ServletContext object. Lservletrequestattributelistener interface method: Øvoid attributeadded

(Servletrequestattributeevent E): Adds a new property to the Request object. Øvoid attributeremoved

(Servletrequestattributeevent E): Removes a property from the Request object. Øvoid attributereplaced

(Servletrequestattributeevent E): The methods in lservletrequestattributeevent of existing property values in a replacement object are: Øjava.lang.string getName () : Returns the name of the property that the request adds, deletes, or replaces Øjava.lang.object getValue (): Returns the value of the attribute that is added, deleted, or replaced by the request L declare it in the Web.xml file in the Web module as follows:

<?xml version= "1.0" encoding= "UTF-8"?>

<web-app>

......

<listener>

<listener-class>pageage.listenerclass</listener-class>

</listener>

......

</web-app>
Use an example to illustrate the use of the Listener L Program requirements Ø through the listener to achieve an online user display and count statistics. Ø User names are added as HttpSession session properties when logged in. Ø After the login to jump to the online first page, showing the name of the currently logged-on user, all the names and number of people online. Ø Listeners can monitor the creation and destruction of ServletContext objects, listen for actions related to httpsession objects, including creating, destroying, and adding, deleting, and modifying attributes. Ø Write all the monitored event logs to TXT file. L Implement process Ø1. Onlinelistener.javaü implements operations Ø2 the properties and ServletContext objects in an HTTP session. Onlineuserlist.javaü saves the current user information and provides ø3 for the corresponding operation of the user's information. Logindo.javaü the user logs on to the Servlet class, gets the user name entered and adds ø4 to the HTTP session properties. Exitdo.jspü the user exits the Servlet class, destroying the user name attribute in the HTTP session ø5. Login.jspü User Login page. The form includes a text box that enters the user name and a Submit button, and form form is submitted to the Logindo servlet for login ø6. Index.jspü to determine whether to log in, not login to jump to the login page. Output Session variable username (currently logged-on user). Obtains the current number of people online through static class Userlist.java (Getusercount) method, Getvector () by static method, obtains the vector object that stores the online users, and then traverses the output of all online user names. • New "Listener" project. L Create a new "Handson.register" package. L Create the Onlinelistener.java listener class under the package and enter the following code in the edit area:


Package handson.register;
Import javax.servlet.ServletContextEvent;
Import Javax.servlet.http.HttpSessionAttributeListener;
Import javax.servlet.http.HttpSessionBindingEvent;
Import javax.servlet.http.HttpSessionEvent;
Import Java.io.FileOutputStream;
Import Java.io.PrintWriter;
Import Java.util.Date;

Import Java.text.SimpleDateFormat; public class Onlinelistener implements httpsessionattributelistener{//write Add and remove property methods public void attributeadded ( 
		Httpsessionbindingevent e) {userlist.adduser (string.valueof (E.getvalue ()));
	System.out.println ("session () + e.getsession (). GetId () +") adds property "+ e.getname () +", value "+ e.getvalue ());	
		public void attributeremoved (Httpsessionbindingevent e) {userlist.removeuser (string.valueof (E.getvalue ()));
	System.out.println ("session () + e.getsession (). GetId () +") removes the attribute "+ e.getname () +", value "+ e.getvalue ());
		//Write Change property method public void attributereplaced (Httpsessionbindingevent e) {String oldvalue=string.valueof (E.getvalue ()); String Newvalue= string.valueof (E.getsession ().
		GetAttribute (E.getname ())); 
		Userlist.removeuser (OldValue);
		Userlist.adduser (NewValue);
	System.out.println ("session () + e.getsession (). GetId () +") property "+ e.getname () +" value, changed from "+oldvalue+" to "+ newvalue"; //write Operation listener method, HTTP session creation listener, public void sessioncreated (Httpsessionevent e) {System.out.println ("create a new Session session (" +e.getse
	Ssion (). GetId () + ")"); The destruction of the//http session listens to the public void sessiondestroyed (Httpsessionevent e) {System.out.println ("Destroy Session sessions ()" +e.getsession ().
	GetId () + ")"); //Write an action context method to listen ServletContext create public void contextinitialized (Servletcontextevent e) {System.out.println ("servletc
	Ontext initialization ... "); }//Monitor ServletContext destroy public void contextdestroyed (Servletcontextevent e) {System.out.println ("ServletContext destroyed ...") 
	...");
		//Write output information method private void print (String message) {printwriter = null; 
			try {out = new PrintWriter (New FileOutputStream ("D:\\log.txt", true); 
				Out.println (NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss").
				Format (new Date ()) + "" + message);
		Out.close ();
		}catch (Exception e) {e.printstacktrace (); }
	}
}

The main code for writing the UserList class is as follows
Package handson.register;
Import Java.util.Vector;

public class UserList {
	private static vector onlineusers=new vector ();
	public static void AddUser (String userName) {
		onlineusers.addelement (userName);
	}
	public static void Removeuser (String userName) {
		onlineusers.removeelement (userName);
	}
	Get online user number public
	static int Getusercount () {return
		onlineusers.size ();
	}
	public static Vector Getvector () {return
		onlineusers
	}} 

Write the user login code in the Logindo class as follows
Package handson.register;

Import java.io.IOException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;

public class Logindo extends HttpServlet {
	private static final long serialversionuid = 1L;
	protected  void DoPost (httpservletrequest req, 
		HttpServletResponse resp) throws ioexception{
		String Username=req.getparameter ("UserName"); 
		HttpSession session=req.getsession ();
		Session.setattribute ("UserName", userName); 
		Resp.sendredirect ("index.jsp");
	}

Exitdo class Write exit login main code as follows
Package handson.register;

Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Exitdo extends Javax.servlet.http.HttpServlet implements Javax.servlet.Servlet {
	private static final Long serialversionuid = 1L;	
	protected void Doget (HttpServletRequest req, 
		HttpServletResponse resp) 		
		throws Servletexception, IOException {
		req.getsession (). RemoveAttribute ("UserName");	
		Resp.sendredirect ("login.jsp");
	}

Configure Logon and Exit Servlet:
<listener>
		<listener-class>
			handson.register.OnlineListener
		</listener-class>
	</listener>
  
  <servlet>
		<servlet-name>loginDo</servlet-name>
		< servlet-class>handson.register.logindo</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>exitDo</servlet-name>
		<servlet-class>handson.register.exitdo</ servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>logindo</ servlet-name>
		<url-pattern>/loginDo</url-pattern>
	</servlet-mapping>
	< servlet-mapping>
		<servlet-name>exitDo</servlet-name>
		<url-pattern>/exitdo</ Url-pattern>
	</servlet-mapping>

Create a login.jsp page
<form method= "POST" action= "Logindo" >
		<center>
			

Write index.jsp page to get the login information code
<body>
    <%
		//If not logged in, turn to login page if
		(Session.getattribute ("UserName") ==null) {
			Response.sendredirect ("login.jsp");
		}
		Vector onlineusers=userlist.getvector (); 
	%>
	

Run Display results:






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.