java web监听程序

来源:互联网 发布:mac快捷键上箭头 编辑:程序博客网 时间:2024/06/05 03:33

java web程序中实现一个监听程序, 定时执行某项业务:

1. 写好监听程序.

2.  在web.xml中配置一个listener,这个listener中可以设置一些初始化参数, 根据业务需要.

监听程序:

import java.util.List;import java.util.Timer;import java.util.TimerTask;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.springframework.web.context.support.WebApplicationContextUtils;/** * 监听程序 * @author yangx * */public class SendParamListener implements ServletContextListener {private SendErrorService sendErrorService;private ParamThread paramThread;class ParamThread extends TimerTask {private boolean isStop = false;@Overridepublic void run() {if (!isStop) {// 这里处理自己的业务System.out.println("线程执行...");}}public void stopThread(){isStop = true;}}public void contextInitialized(ServletContextEvent event) {//ServletContext sc = event.getServletContext();//sendErrorService = (SendErrorService) WebApplicationContextUtils.getWebApplicationContext(sc).getBean("sendErrorService");paramThread = new ParamThread();Timer timer = new Timer();timer.schedule(paramThread, 1000, Constants.getPARAM_SEND_DATE()*1000);}public void contextDestroyed(ServletContextEvent event) {paramThread.stopThread();}}

web.xml中配置程序:

<listener><listener-class>SendParamListener</listener-class></listener>
可以在listener之前设置一些初始化参数:

<context-param><param-name>参数名</param-name><param-value>参数值</param-value></context-param>
然后在程序初始化方法中使用:

event.getServletContext().getInitParameter("参数名");
获取参数值处理自己的相关业务

0 0
原创粉丝点击