1. Learning Objectives
1. Listener listener
2. Listener listener role
3. Creation and destruction of Listener listeners
2. Key Knowledge
In order to get the Filter program on the web. Configuration information in the XML file, Servlet API provides a FilterConfig interface that encapsulates the filter program on the web. All the registration information in the XML and provides a series of ways to get this configuration information.
1. Listener listener
Filter and Listener are two advanced features of the Servlet specification that differ from Servlet in that they are not used to process client requests. Filter is used to modify request, response objects, and Listener is used to listen for context, session, request events. Making good use of these two advanced features in the Servlet specification can easily solve some special problems.
2. Listener listener role
Is listening for application startup and shutdown, needs to be implemented ServletContextListener Interface; Is listening session Creation and destruction; The addition, removal, and change of attributes require implementation HttpSessionListener and HttpSessionAttributeListener Interface.
2.1 is the HttpSessionBindingListener interface
First: Implement ServletContextListener An interface has two methods: (1)public void contextInitialized(ServletContextEvent sce); //Apply Startup Event (2)public void contextDestroyed(ServletContextEvent sce); //Apply Stop Event Second: Realization HttpSessionListener and HttpSessionAttributeListener Interface 1)HttpSessionListener Interfaces have two methods: (1)public void sessionCreated(HttpSessionEvent httpsessionevent); (2)public void sessionDestroyed(HttpSessionEvent httpsessionevent); 2)HttpSessionAttributeListener Interfaces have three methods: (1)public void attributeAdded(HttpSessionBindingEvent httpsessionbindingevent); (2)public void attributeRemoved(HttpSessionBindingEvent httpsessionbindingevent); (3)public void attributeReplaced(HttpSessionBindingEvent httpsessionbindingevent);
3. Listener listens for creation and destruction of three domain objects
3.1 Listening for creation and destruction of ServletContext domain objects: Implementing the ServletContextListener interface
Lifecycle of the ServletContext domain object:
Create: Created when the server is started
Destroy: Close the server or remove the project from the server
@WebListener public class MyServletContextListener implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("Initialization"); } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("Destroyed"); } }
Effect:
Use the ServletContextListener listener to do some work that you want to initialize or perform custom task scheduling when you create a ServletContext domain object.
3.2 Listens for the creation and destruction of ServletRequest domain objects: Implements the ServletRequestListener interface.
Lifecycle of ServletRequest domain objects:
Create: Any resource accessing the server will send a request (ServletRequest) to appear, access. html and. jsp and. Servlets create requests.
Destroy: The server has responded to this request.
@WebListener public class MyServletRequestListener implements ServletRequestListener{ @Override public void requestDestroyed(ServletRequestEvent arg0) { System.out.println("ServletRequest Destroyed"); } @Override public void requestInitialized(ServletRequestEvent arg0) { System.out.println("ServletRequest Created"); } }
3.3 Listening for the creation and destruction of HttpSession domain objects: Implementing the HttpSessionListener interface:
Lifecycle of HttpSession domain objects:
Create: As long as the getSession() method is called, it will be created, and a session will only be created once.
Destroy: 1. Timeout (default 30 minutes) 2. Abnormal shutdown, destroy 3. Server shutdown normally (serialization)
@WebListener public class MyHttpSessionListener implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent arg0) { System.out.println("HttpSession Created"); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { System.out.println("HTTPSession Destroyed"); } }
What it does: Each user logs in to the website with an HTTPSession object, which counts the number of people online.
- Listener listens for changes in the state of properties of three domain objects
Listen for changes to the HttpSession property: Implement the HttpSessionAttributeListener interface.
Listen for changes to the ServletContext property: Implement the ServletContextAttribute interface.
Listen for changes to the ServletRequest property: Implement the ServletRequestAttribute interface.
3. Practical application
1. Create a listener:
Create a Chapter11 in chepter11. Listener package, which writes a mylistener class to implement several listener interfaces.
Code example:
mylistener.java package chapter11.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * Application Lifecycle Listener implementation class mylistener * */ @WebListener public class mylistener implements ServletContextListener, HttpSessionListener, ServletRequestListener { /** * Default constructor. */ /** * @see HttpSessionListener#sessionCreated(HttpSessionEvent) */ public void sessionCreated(HttpSessionEvent arg0) { // TODO Auto-generated method stub System.out.println("servletsession Created"); } /** * @see ServletRequestListener#requestDestroyed(ServletRequestEvent) */ public void requestDestroyed(ServletRequestEvent arg0) { // TODO Auto-generated method stub System.out.println("servletrequest Destroyed"); } /** * @see ServletRequestListener#requestInitialized(ServletRequestEvent) */ public void requestInitialized(ServletRequestEvent arg0) { // TODO Auto-generated method stub System.out.println("servletrequest Created"); } /** * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent) */ public void sessionDestroyed(HttpSessionEvent arg0) { // TODO Auto-generated method stub System.out.println("servletsession Destroyed"); } /** * @see ServletContextListener#contextDestroyed(ServletContextEvent) */ public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub System.out.println("servletcontext Destroyed"); } /** * @see ServletContextListener#contextInitialized(ServletContextEvent) */ public void contextInitialized(ServletContextEvent arg0) { // TODO Auto-generated method stub System.out.println("servletcontext Created"); } }
Add a listening information class on the web. Add mylistener event listener information to the XML file:
<listener> <listener-class> chapter11.listener.mylistener </listener-class> </listener>
Operation Display:
Set monitoring timeout information;
On the web. Timeout for session set in XML file is 2 min
<session-config> <session-timeout>2</session-timeout> </session-config>
Operation Display:
2. Create a test page:
Create a new testattribute in chepter11. JSP is used to observe the role of the attribute event listener.
Code example:
<?xml version="1.0" encoding="UTF-8" ?> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Insert title here</title> </head> <body> <h3>This is the page of the test object property information listener</h3> <% getServletContext().setAttribute("username", "itcast"); getServletContext().setAttribute("username", "itheima"); getServletContext().removeAttribute("username"); session.setAttribute("username", "itcast"); session.setAttribute("username", "itheima"); session.removeAttribute("username"); request.setAttribute("username", "itcast"); request.setAttribute("username", "itheima"); request.removeAttribute("username"); %> </body> </html>
Create a listener at chapter11. Create myattributelistener in listener. Listener class for java.
Code example:
package chapter11.listener; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletRequestAttributeEvent; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; /** * Application Lifecycle Listener implementation class myattributelistener * */ @WebListener public class myattributelistener implements ServletContextAttributeListener, HttpSessionAttributeListener, ServletRequestAttributeListener { /** * Default constructor. */ public myattributelistener() { // TODO Auto-generated constructor stub } /** * @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent) */ public void attributeAdded(ServletContextAttributeEvent sae) { // TODO Auto-generated method stub String name = sae.getName(); System.out.println("servletcontext Add Attributes:"+ name + "="+sae.getServletContext().getAttribute(name)); } /** * @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent) */ public void attributeRemoved(ServletContextAttributeEvent sae) { // TODO Auto-generated method stub String name = sae.getName(); System.out.println("servletcontext Remove Attribute:"+name); } /** * @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent) */ public void attributeRemoved(ServletRequestAttributeEvent sra) { // TODO Auto-generated method stub String name = sra.getName(); System.out.println("servletrequest Remove Attribute"+name); } /** * @see ServletRequestAttributeListener#attributeAdded(ServletRequestAttributeEvent) */ public void attributeAdded(ServletRequestAttributeEvent sra) { // TODO Auto-generated method stub String name = sra.getName(); System.out.println("servletrequest Add Attributes:"+ name + "="+sra.getServletRequest().getAttribute(name)); } /** * @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent) */ public void attributeReplaced(ServletRequestAttributeEvent sra) { // TODO Auto-generated method stub String name = sra.getName(); System.out.println("servletrequest Replace Properties:"+ name + "="+sra.getServletRequest().getAttribute(name)); } /** * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent) */ public void attributeAdded(HttpSessionBindingEvent hbe) { // TODO Auto-generated method stub String name = hbe.getName(); System.out.println("httpsession Add Attributes:"+ name + "="+hbe.getSession().getAttribute(name)); } /** * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent) */ public void attributeRemoved(HttpSessionBindingEvent hbe) { // TODO Auto-generated method stub String name = hbe.getName(); System.out.println("httpsession Remove Attribute:"+name); } /** * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent) */ public void attributeReplaced(HttpSessionBindingEvent hbe) { // TODO Auto-generated method stub String name = hbe.getName(); System.out.println("httpsession Replace Properties:"+ name + "="+hbe.getSession().getAttribute(name)); } /** * @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent) */ public void attributeReplaced(ServletContextAttributeEvent sea) { // TODO Auto-generated method stub String name = sea.getName(); System.out.println("servletcontext Replace Properties:"+ name + "="+sea.getServletContext().getAttribute(name)); } }
Add listening information on the web. Enter something into the XML file:
<listener> <listener-class> chapter11.listener.myattributelistener </listener-class> </listener>
Operation Display: