验证码功能实现
本案例使用线程池实现定时任务,并修改数据库.
1.首先得到用户id和验证码code,并存入数据库(这里使用的hibnate框架)
baseDao.executeBySql("update xt_nation set code= '"+ code +"' where id = "+ id +" ");
2.自定义线程池进行延时任务
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
Runnable task =new Runnable(){
@SneakyThrows
@Override
public void run() {
System.out.println("开始执行延时任务--删除超时验证码");
temporarySql(id,password);
System.out.println("延时任务执行完成--删除成功");
}
};
threadPool.schedule(task,1,TimeUnit.MINUTES);
注:scheduledThreadPool.scheduleAtFixedRate(task,10,1000,TimeUnit.MILLISECONDS);// 延迟10ms后、每隔1000ms执行任务—-可以设置循环执行
3.线程池延时任务访问数据库需要使用jdbc
3.1读取config配置文件
ResourceBundle resource = ResourceBundle.getBundle("config");
//调用静态方法直接获得键值对中值
String url = resource.getString("jdbc.url");//url
String user = resource.getString("jdbc.username");//user
String pwd = resource.getString("jdbc.password");//pwd
3.2执行sql,并关闭连接
//1、加载驱动(固定写法)
Class.forName("com.mysql.jdbc.Driver");
//3、连接成功,数据库对象(固定写法)
Connection connection = DriverManager.getConnection(url, user, pwd);
//4、执行sql的对象(固定写法)
Statement statement = connection.createStatement();
//5、执行sql语句,返回结果集
String sql="delete from xt_nation where id = "+ id +" ";
int resultSet = statement.executeUpdate(sql);
if(resultSet > 0){
System.out.println("过期验证码已删除");
}else {
System.out.println("过期验证码删除失败");
}
statement.close();
connection.close();
注:statement的创建,修改,删除操作均可使用
executeUpdate
staement的查询操作可以使用 executeQuery
还没有评论,来说两句吧...