Systemlistener
Import Java.util.timer;import java.util.timertask;import java.util.uuid;import javax.servlet.ServletContextEvent; Import Javax.servlet.servletcontextlistener;import Cn.itcast.web.dao.systemdao;public class SystemListener Implements Servletcontextlistener {Private Timer timer = new timer (); public void contextinitialized (Servletcontextevent sce) {try {Systemdao Systemdao = new Systemdao (); Systemdao.createtable ("Systeminit"); Timer.schedule (New Systemtask (), 0,5*1000); } catch (Exception e) {}} public void contextdestroyed (Servletcontextevent sce) {try {S Ystemdao Systemdao = new Systemdao (); Systemdao.droptable ("Systeminit"); Abort timer timer.cancel (); } catch (Exception e) {}}}//Task Class class Systemtask extends timertask{public void run () {try { Systemdao Systemdao = new Systemdao (); Systemdao.init ("Systeminit", Uuid.randoMuuid (). toString ()); } catch (Exception e) {}}}
Table
*/import java.sql.SQLException;import org.apache.commons.dbutils.QueryRunner;import cn.itcast.web.util.JdbcUtil;public class SystemDao { //删除表 public void dropTable(String tableName) throws SQLException{ QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource()); String sql = "drop table if exists " + tableName; runner.update(sql); } //创建表 public void createTable(String tableName) throws SQLException{ QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource()); String sql = "create table if not exists "+tableName+"(id varchar(40) primary key,curr_time timestamp not null)"; runner.update(sql); } //初始化数据 public void init(String tableName,String id) throws SQLException{ QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource()); String sql = "insert into "+tableName+"(id) values(?)"; runner.update(sql,id); }}
Web. XML configuration
The web inserts a record into the database every 5 seconds-Learn notes