Realization and Application of ServletContextListener Interface

xiaoxiao2021-03-06  57

The servletContextListener interface has two ways to implement: contextInitialized () and contextdestroyed ();

Listener, translated as a listener. As the name suggests, it listens to the servlet container. When the application starts, it will call the conteitialized () method; when the app is closed, it also calls the contedentroyed () method.

We can use this feature to initialize some information, of course, we can also use the servlet class init () method, and execute when it starts the application in the configuration file, and execute the destroy () method when it is closed. But inherits this interface It should be more in line with the application of the container.

For a simple example: In some forums, communities and chat rooms, deleting online timeout users can use this interface to implement. You can use Java's Timertask and Timer classes to implement automatic detection every other time. Instance code As follows: UseronlineTimertask.java ------------------ package com.bcxy.servlet;

Import java.util.timertask;

Import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory;

Public Class UseronlineTimertask Extends Timertask {

Log log = logfactory.getlog (useronlinetimertask.class); public void run () {// Remove timeout online user log.info ("Delete Online Timeout Users ...");

}

} ------------------------------------- ----------------------- Syslistener.java ------------------------ ----------- Package com.bcxy.servlet;

Import java.io.ioException; import java.util.timer;

import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet;

Import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory;

Public class syslistenerextends httpservletimplements servletContextListener {log log = logfactory.getlog (syslistener.class); Timer Timer = new timer ();

public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException {//} public void contextInitialized (ServletContextEvent sce) {log.info ( "initial context ...."); timer.schedule (new UserOnlineTimerTask (), 0 , 10000);

} public void contextdestroyed (servletContexTevent SCE) {log.info ("Destory Context ...."); Timer.Cancel ();}

} -------------------------------- If you don't use log4j, you can change Log.info () to System.out.println () will get the same result. If you want to configure log4j, please click on the log record.

If you have any questions, please contact me: Webmaster@bcxy.com

Source: http://www.bcxy.com/java/listener.htm

转载请注明原文地址:https://www.9cbs.com/read-113381.html

New Post(0)