The listener in Javaweb is a special class defined in the servlet specification that listens to the creation and destruction events of ServletContext, HttpSession, and ServletRequest domain objects in a Web application. and listening for events in which the properties in these domain objects have been modified.
Httpsessionlistener interface for monitoring the creation and destruction of HttpSession objects
When creating a session, sessioncreated (Httpsessionevent se);
When a session is destroyed, sessiondestroyed (Httpsessionevent se).
1. Write the source code to monitor the creation and destruction of HttpSession domain objects
Implement Httpsessionlistener interface, monitor the creation and destruction of HttpSession objects
PackageCom.servlet.listener;ImportJavax.servlet.http.HttpSessionEvent;ImportJavax.servlet.http.HttpSessionListener;/** * Simple implementation of the Httpsessionlistener interface, can be httpsession object creation and destruction of these two actions to listen. * @author Fan Fangming * * Public class Easyhttpsessionlistenerimplements Httpsessionlistener{ @Override Public void sessioncreated(Httpsessionevent se) {System.out.println ("-------"+ se.getsession () +", HttpSession object Creation"); }@Override Public void sessiondestroyed(Httpsessionevent se) {System.out.println ("-------"+", HttpSession object Destruction"); }}
2. Modify Web. xml
<listener> <description>Httpsessionlistener Listener</Description> <listener-class>Com.servlet.listener.EasyHttpSessionListener</listener-class> </listener> <session-config> <!--Configure HttpSession objects after 1 minutes of destruction-- <session-timeout>1</session-timeout> </session-config>"Note: This setting<session-timeout>1</session-timeout>Indicates that the session expires after one minute, where the unit of time is minutes; 3. Modify index.jsp for testing<%@ page language="java" import="java.util.*" pageencoding= "UTF-8"%><! DOCTYPE html><html> <head> <title>My JSP ' index.jsp ' starting page</title> </head> <body>This is my JSP page.<br>To access the JSP page, the HttpSession is created with the following ID: ${pagecontext.session.id}</body></html>
4. Operation result
Start Web middleware, access from URL:
http://127.0.0.1:8080/webStudy/index.jsp
See the output on the page:
This is my JSP page.
To access the JSP page, the HttpSession is created with the following ID: d18a1e95ae0a58c82e5984f6d6e12ae3
Look at the console:
--[email Protected],httpsession Object creation
Because we set the expiration time of 1 minutes, so by the way to brew a cup of tea to drink, gently blow the bubble above the cup, and then see the destruction program executed.
——-, HttpSession object destruction
A good memory is better than a bad pen. 40-javaweb application in HttpSession domain monitoring (4)