1. Two methods for implementing the javax. servlet. ServletContextListener interface: contextInitialized () and contextDestroyed ()
ContextInitialized (): executed when the Servlet container starts
ContextDestroyed (): executed when the Servlet container is stopped
2. Add the program to be listened to in contextInitialized (), and control the execution frequency of the listener by using the schedule () method of java. util. Timer.
DEMO: This is a prototype of my text message reply listener. It is simplified)
ReplyListener. java
- package com.hanweb.jcms;
-
- import javax.servlet.*;
-
- public class ReplyListener implements ServletContextListener {
- private ReplyTimer rt = null;
- public void contextInitialized(ServletContextEvent event) {
- String status = "[SYS] SMS reply listener start .";
- event.getServletContext().log(status);
- System.out.println(status);
-
- rt = new ReplyTimer(1);
- rt.start();
- }
-
- public void contextDestroyed(ServletContextEvent event) {
- String status = "[SYS] SMS reply listener stop .";
- event.getServletContext().log(status);
- System.out.println(status);
-
- if (rt != null) {
- rt.stop();
- }
- }
- }
ReplyTimer. java
- package com.hanweb.jcms;
-
- import java.util.*;
-
- public class ReplyTimer {
- private final Timer timer = new Timer();
- private final int min;
-
- public ReplyTimer(int minutes) {
- min = minutes;
- }
-
- public void start() {
- Date date = new Date();
- timer.schedule(new ReplyTask(), date, min * 60 * 1000);
- }
-
- public void stop() {
- timer.cancel();
- }
- }
ReplyTask. java
- package com.hanweb.jcms;
-
- import java.util.*;
-
- public class ReplyTask extends TimerTask {
- public void doSomething() {
- System.out.println("[SYS] SMS reply listener running ");
- }
-
- public void run() {
- doSomething();
- }
- }
Put the compiled class file into the WEB-INF/classes, and finally do not forget to add the listening statement to the WEB. xml of the current web application in the Servlet container:
- <listener>
- <listener-class>com.hanweb.jcms.ReplyListener</listener-class>
- </listener>
- How to install Apache Servlet
- Optimize Servlet configuration for web. xml slimming
- How to configure Servlet in XML
- Solve the Problem of Servlet JSP page garbled
- Servlet and JSP security issues