web每5秒向數(shù)據(jù)庫(kù)中插入一條記錄-學(xué)習(xí)筆記
標(biāo)簽:
JavaScript
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 { SystemDao systemDao = new SystemDao(); systemDao.dropTable("systemInit"); //中止定时器 timer.cancel(); } catch (Exception e) { } }}//任务类class SystemTask extends TimerTask{ public void run() { try { SystemDao systemDao = new SystemDao(); systemDao.init("systemInit",UUID.randomUUID().toString()); } catch (Exception e) { } }}
表
*/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配置
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦