直接上代码吧,高手们帮我看看
web.xml:
- XML code
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <listener> <listener-class>test.timer.TimerListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
- Java code
package test.timer;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class TimerListener implements ServletContextListener { @SuppressWarnings("unused") private ServletContext servletContext = null; private Timer timer = null; /** * 开始执行 */ @Override public void contextInitialized(ServletContextEvent e) { e.getServletContext().log("init !"); timer = new Timer(true); // 获得当天的日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "); Date date = new Date(); // 定义开始时间字符串 String timeStr = "12:00:00"; timeStr = sdf.format(date) + timeStr; // 获得当天的指定时间的date对象 sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); try { date = sdf.parse(timeStr); } catch (ParseException e1) { e1.printStackTrace(); } // 判断今天的执行时间是否已经过去,如果过去则改为明天 if (date.getTime() < System.currentTimeMillis()) { date = new Date(date.getTime() + 24 * 60 * 60 * 1000); } timer.schedule(new TestTimer(), date, 24*60*60 * 1000); } /** * 销毁 */ @Override public void contextDestroyed(ServletContextEvent e) { timer.cancel(); e.getServletContext().log("destroyed"); }}
环境没有问题,如果web.xml去掉<listener>可以正常启动。项目就这么几个文件
------解决方案--------------------
试了一下,可以启动.你这个错误是java.lang.ClassNotFoundException: test.timer.TimerListener
啊,你把项目重新编译,然后在web服务器上重新发布下.