Java实现邮箱验证

1.Java实现用户注册,邮箱验证码激活的核心代码:

(1) 在RegisterServlet 用户注册类中

成都创新互联公司专业为企业提供义马网站建设、义马做网站、义马网站设计、义马网站制作等企业网站建设、网页设计与制作、义马企业网站模板建站服务,10余年义马做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName=request.getParameter("username"); String password=request.getParameter("password"); String email=request.getParameter("email"); System.out.println(userName+" "+password+" "+email); UserService userService=new UserServiceImpl(); if(userService.doRegister(userName,password,email)){ request.setAttribute("msg", "注册成功,请登录邮箱激活账号"); }else{ request.setAttribute("msg", "注册失败,请检查相关信息"); } request.getRequestDispatcher("/result.jsp").forward(request, response); } }

(2) 在ActiveServlet 邮箱验证中:

public class ActiveServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code=request.getParameter("code"); UserService userService=new UserServiceImpl(); if(userService.activeUser(code)){ request.getRequestDispatcher("/welcome.jsp").forward(request, response); }else{ request.getRequestDispatcher("/fail.jsp").forward(request, response); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

(3) 在UserService中

public interface UserService { boolean doRegister(String userName, String password, String email); boolean activeUser(String code); }

(4) 在UserServiceImpl中

public class UserServiceImpl implements UserService { public boolean doRegister(String userName, String password, String email) { // 这里可以验证各字段是否为空 //利用正则表达式(可改进)验证邮箱是否符合邮箱的格式 if(!email.matches("^\\w+@(\\w+\\.)+\\w+$")){ return false; } //生成激活码 String code=CodeUtil.generateUniqueCode(); User user=new User(userName,email,password,0,code); //将用户保存到数据库 UserDao userDao=new UserDaoImpl(); //保存成功则通过线程的方式给用户发送一封邮件 if(userDao.save(user)>0){ new Thread(new MailUtil(email, code)).start();; return true; } return false; } public boolean activeUser(String code) { UserDao userDao=new UserDaoImpl(); if(userDao.activeUser(code)>0){ return true; }else{ return false; } } }

(5) 在UserDao中

public interface UserDao { int save(User user); int activeUser(String code); }

(6) 在UserDaoImpl中

public class UserDaoImpl implements UserDao{ public int save(User user) { int num=0; try { Connection conn=DBUtil.getConnection(); String sql ="insert into user(username,email,password,state,code) values(?,?,?,?,?)"; PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setString(1, user.getUserName()); pstmt.setString(2, user.getEmail()); pstmt.setString(3, user.getPassword()); pstmt.setInt(4, user.getState()); pstmt.setString(5, user.getCode()); num=pstmt.executeUpdate(); DBUtil.close(conn,pstmt, null); } catch (SQLException e) { e.printStackTrace(); } return num; } public int activeUser(String code) { int num=0; try { Connection conn=DBUtil.getConnection(); String sql="update user set state=1 where code=?"; PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setString(1, code); num=pstmt.executeUpdate(); DBUtil.close(conn,pstmt,null); } catch (SQLException e) { e.printStackTrace(); } return num; } }

(7) 在CodeUtil中

public class CodeUtil { //生成唯一的激活码 public static String generateUniqueCode(){ return UUID.randomUUID().toString().replaceAll("-", ""); } }

(8) 在 MailUtils中

public class MailUtil implements Runnable { private String email;// 收件人邮箱 private String code;// 激活码 public MailUtil(String email, String code) { this.email = email; this.code = code; } public void run() { // 1.创建连接对象javax.mail.Session // 2.创建邮件对象 javax.mail.Message // 3.发送一封激活邮件 String from = "xxx@qq.com";// 发件人电子邮箱 String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易) Properties properties = System.getProperties();// 获取系统属性 properties.setProperty("mail.smtp.host", host);// 设置邮件服务器 properties.setProperty("mail.smtp.auth", "true");// 打开认证 try { //QQ邮箱需要下面这段代码,163邮箱不需要 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); // 1.获取默认session对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("xxx@qq.com", "xxx"); // 发件人邮箱账号、授权码 } }); // 2.创建邮件对象 Message message = new MimeMessage(session); // 2.1设置发件人 message.setFrom(new InternetAddress(from)); // 2.2设置接收人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); // 2.3设置邮件主题 message.setSubject("账号激活"); // 2.4设置邮件内容 String content = "

这是一封激活邮件,激活请点击以下链接

http://localhost:8080/RegisterDemo/ActiveServlet?code=" + code + "

"; message.setContent(content, "text/html;charset=UTF-8"); // 3.发送邮件 Transport.send(message); System.out.println("邮件成功发送!"); } catch (Exception e) { e.printStackTrace(); } } }

(2)在AdminUserService中:

@Service public class AdminUserService { @Autowired private AdminUserDao adminUserDao; @Autowired private AdminAuthDao adminAuthDao; private static String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串 private static long expireTime = 24 * 60 * 60 * 1000; public static String generateVcode(String cellphone) { StringBuilder tmp = new StringBuilder(); Random rand = new Random(); for (int i = 0; i < 6; i++) { tmp.append(getRandomString(rand.nextInt(36))); } return tmp.toString(); } public static String getRandomString(int num){ return String.valueOf(randString.charAt(num)); } /** * 邮箱发送验证码 * @param userEmail * @return */ public String genSendVecode(String userEmail) { // 1. 校验邮箱是否正确 // 2. 校验邮箱是否合法 // 3. 生成验证码 // 4. 将验证码发送至指定邮箱 if (!RegexUtil.emailVerify(userEmail) || !userEmail.endsWith("@wolaibao.com") || !userEmail.endsWith("@zhongbao.email") ) { throw new WlbException("用户账户错误,请重新输入"); } AdminUser adminUser = findAdminByAccount(userEmail); if (null == adminUser || StringUtils.isBlank(adminUser.getUsername()) || adminUser.getStatus()!=0) { throw new WlbException("用户账户错误,请重新输入"); } AdminAuth lastAuth = adminAuthDao.selectLastVcode(userEmail); if (lastAuth != null && System.currentTimeMillis() - lastAuth.getUpdateTime().getTime() < (1 * 60 * 1000)) { throw new WlbException("验证码已经发送至邮箱请勿重复获取"); } String vcode; if (lastAuth == null || System.currentTimeMillis() - lastAuth.getExpireTime() > 0) { vcode = generateVcode(userEmail); AdminAuth adminAuth = new AdminAuth(); adminAuth.setEmail(userEmail); adminAuth.setVcode(vcode); adminAuth.setExpireTime(System.currentTimeMillis() + expireTime); adminAuthDao.insert(adminAuth); } else { vcode = lastAuth.getVcode(); adminAuthDao.update(lastAuth); } MsgService.sendMail(userEmail, "管理后台登录验证", "管理后台登录验证码为:" + vcode + "n有效期为24小时!"); return "我有效期为24来保管理后台登录验证已经发送至邮箱,小时,请注意保管验证码"; } private AdminUser findAdminByAccount(String userEmail) { return adminUserDao.selectByAccount(userEmail); } }


标题名称:Java实现邮箱验证
网页URL:
http://myzitong.com/article/cppioh.html