5分钟时效性验证码实现:
验证码对象,包含两个成员变量 验证码和时间
package common;
import java.io.Serializable;
import java.time.Duration;
import java.time.LocalTime;
public class Code implements Serializable {
private String code;
private LocalTime now;
public Code(String code){
this.code=code;
now=LocalTime.now();
}
public static boolean judge(Code code1,Code code2){
if(code1.getCode().equals(code2.getCode())){
Duration duration = Duration.between(code1.getNow(), code2.getNow());
long totalSeconds = duration.getSeconds(); // 获取总秒数
long hours = totalSeconds / 3600; // 计算小时数
long minutes = (totalSeconds % 3600) / 60;// 计算分钟数
long seconds = totalSeconds % 60; // 计算剩余的秒钟数
System.out.println("相差"+minutes+"分"+seconds+"秒");
if(hours==0&&minutes<=5){
return true;
}else{
return false;
}
}else{
return false;
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LocalTime getNow() {
return now;
}
}
judge方法用与判断是否过时
在获取验证码时,
服务端将用户的邮箱和验证码对象放入hashMap, 在客户端点击注册时,会将用户邮箱和验证码的等信息打包发送过去,届时调用judge即可
package util;
import common.Code;
import java.util.HashMap;
public class ControlUserCode {
private static HashMap <String,Code> hashMap=new HashMap<>();
public static void addCode(String id, Code code){
hashMap.put(id,code);
}
public static Code getCode(String id){
return hashMap.get(id);
}
}
创建课程
客户端将需要创建的课程打包发送给服务端,服务端连接数据库,添加记录。
package dao;
import common.Course;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class NewClass {
private static Connection conn=DataBaseConnect.getConn();
private static String sql="INSERT INTO course (id,name,teacherId,teacherName) VALUES(?,?,?,?)";
private static PreparedStatement pstmt;
static {
try {
pstmt=conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static boolean newClass(Course course){
try {
pstmt.setString(1,course.getId());
pstmt.setString(2, course.getName());
pstmt.setString(3,course.getTeacherId());
pstmt.setString(4,course.getTeacherName());
pstmt.executeUpdate();
} catch (Exception e) {
System.out.println("新建课程失败");
return false;
}
System.out.println("新建课程成功");
return true;
}
}