日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java实现邮箱激活注册账号完整案例

發布時間:2023/12/8 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java实现邮箱激活注册账号完整案例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

項目業務流程介紹:1.用戶填寫用戶名,郵箱,注冊密碼,提交注冊信息(此時還不能登錄系統)。2.系統通過一個已配置好的QQ郵箱賬號向剛剛注冊的QQ郵箱發送激活郵件,郵件內容包含激活鏈接。3.注冊用戶登錄QQ郵箱點擊激活鏈接進行激活賬號操作。4.系統自動跳轉到登錄界面,用戶進行登陸操作

一,前期準備?

1.兩個QQ郵箱,并且用于發送激活郵件的qq郵箱需要進行如下配置,進入QQ郵箱首頁(網頁版)點擊設置下面的賬戶

下拉找到??POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務 打開 POP3/SMTP服務,并記住授權碼,后面發送郵件時會用到授權碼

2.軟件:jdk,eclipsse,oracle?

3.驅動包:oracle驅動包,mail jar包

4.數據庫腳本:

create table personinfo(id int primary key,name varchar2(50), email varchar2(50),password varchar2(50),state int , actcode varchar2(100))--創建遞增序列 create sequence seq_personInfo_id start with 1;

5.說明;我這里采用JNDI方式在tomcat里配置數據源,如果不知道的可以見我的博客https://mp.csdn.net/postedit/86493281

?介紹了如何配置數據源的方法

二,項目搭建

1.新建名為 java mail的java項目,項目包結構如下??

2.web.xml配置如下

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"><display-name>javamail</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><servlet><servlet-name>registServlet</servlet-name><servlet-class>com.mail.servlet.RegistServlet</servlet-class></servlet><servlet-mapping><servlet-name>registServlet</servlet-name><url-pattern>/regist</url-pattern></servlet-mapping><servlet><servlet-name>activeServlet</servlet-name><servlet-class>com.mail.servlet.ActiveServlet</servlet-class></servlet><servlet-mapping><servlet-name>activeServlet</servlet-name><url-pattern>/active</url-pattern></servlet-mapping><servlet><servlet-name>loginServlet</servlet-name><servlet-class>com.mail.servlet.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>loginServlet</servlet-name><url-pattern>/login</url-pattern></servlet-mapping> </web-app>

實體類 PersonInfo代碼如下

package com.mail.pojo;import java.io.Serializable;public class PersonInfo implements Serializable {private static final long serialVersionUID = -3801437971749236561L;private Integer id; // 主鍵private String name; // 用戶名private String mail; // 郵箱地址private String password; // 登錄密碼private Integer state; // 狀態碼 0:未激活 1:激活private String actcode; // 激活碼public PersonInfo() {super();// TODO Auto-generated constructor stub}public PersonInfo(Integer id, String name, String mail, String password, Integer state, String actcode) {super();this.id = id;this.name = name;this.mail = mail;this.password = password;this.state = state;this.actcode = actcode;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getMail() {return mail;}public void setMail(String mail) {this.mail = mail;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getState() {return state;}public void setState(Integer state) {this.state = state;}public String getActcode() {return actcode;}public void setActcode(String actcode) {this.actcode = actcode;}@Overridepublic String toString() {return "PersonInfo [id=" + id + ", name=" + name + ", mail=" + mail + ", password=" + password + ", state="+ state + ", actcode=" + actcode + "]";}}

3.進入注冊界面 regist.jsp,填寫表單 提交到 RegistServlet? regist.jsp代碼如下

<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>注冊</title> </head> <body> <h2>注冊頁面</h2> <hr/> <form method="POST" action="regist"> <table><tr><td><label for="name">用戶名:</label></td><td><input type="text" name="name" id="name" /></td></tr><tr><td><label for="password">密碼:</label></td><td><input type="password" name="password" id="password" /></td></tr><tr><td><label for="mail">郵箱:</label></td><td><input type="email" name="mail" id="mail"/></td><tr><td colspan="2"><input type="submit" value="注冊" /></td></tr> </table> </form> </body> </html>

4.RegistServlet獲取表單注冊信息,發送給業務層注冊處理類PersonInfoBusiness 進行處理?RegistServlet類代碼如下

package com.mail.servlet;import java.io.IOException; import java.util.UUID;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import com.mail.business.PersonInfoBusiness; import com.mail.pojo.PersonInfo;public class RegistServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");String name = request.getParameter("name");String mail = request.getParameter("mail");String password = request.getParameter("password");PersonInfo personInfo = new PersonInfo();personInfo.setName(name);personInfo.setMail(mail);personInfo.setPassword(password);personInfo.setState(0);personInfo.setActcode(UUID.randomUUID().toString());// 生成唯一激活碼// 把激活碼存進sessionHttpSession session = request.getSession();session.setAttribute("actcode", personInfo.getActcode());PersonInfoBusiness personInfoBusiness = new PersonInfoBusiness();if (personInfoBusiness.regist(personInfo) == 1) {request.setAttribute("msg", "注冊成功,請登錄郵箱激活賬號");} else {request.setAttribute("msg", "注冊失敗,請檢查相關信息");}request.getRequestDispatcher("/result.jsp").forward(request, response);}}

?

5.業務層PersonInfoBusiness 類調用數據層PersonInfoDao類將注冊信息存儲進數據庫,賬號狀態設置為 0 (未激活狀態),同時調用MailUtil類發送激活郵件

PersonInfoBusiness 類代碼如下

package com.mail.business;import com.mail.dao.PersonInfoDao; import com.mail.pojo.PersonInfo; import com.mail.util.MailUtil;public class PersonInfoBusiness {public int regist(PersonInfo personInfo) {PersonInfoDao personInfoDao = new PersonInfoDao();int result = personInfoDao.regist(personInfo);if(result == 1){ //注冊成功,發送一封激活郵件MailUtil.sendMail(personInfo.getMail(), personInfo.getActcode());}return result;}public int active(String actcode) {PersonInfoDao personInfoDao = new PersonInfoDao();int result = personInfoDao.active(actcode);return result;}public int login(PersonInfo personInfo) {PersonInfoDao personInfoDao = new PersonInfoDao();int result = personInfoDao.login(personInfo);if(result == 1){ //注冊成功,發送一封激活郵件MailUtil.sendMail(personInfo.getMail(), personInfo.getActcode());}return result;} }

PersonInfoDao 類代碼如下

package com.mail.dao;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;import com.mail.pojo.PersonInfo; import com.mail.util.DBUtil;public class PersonInfoDao {/*** 添加注冊信息* * @param personInfo* @return*/public int regist(PersonInfo personInfo) {int result = 0;Connection conn = null;PreparedStatement pstmt = null;try {conn = DBUtil.getConnection();String sql = "insert into PersonInfo values(seq_personInfo_id.nextval,?,?,?,?,?)";pstmt = conn.prepareStatement(sql);pstmt.setString(1, personInfo.getName());pstmt.setString(2, personInfo.getMail());pstmt.setString(3, personInfo.getPassword());pstmt.setInt(4, personInfo.getState());pstmt.setString(5, personInfo.getActcode());result = pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(null, pstmt, conn);}return result;}/*** 激活賬號* * @param actcode* @return*/public int active(String actcode) {int result = 0;Connection conn = null;PreparedStatement pstmt = null;try {conn = DBUtil.getConnection();String sql = "update PersonInfo set state=1 where actcode=?";pstmt = conn.prepareStatement(sql);pstmt.setString(1, actcode);result = pstmt.executeUpdate();DBUtil.close(null, pstmt, conn);} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(null, pstmt, conn);}return result;}/*** 登錄* * @param personInfo* @return*/public int login(PersonInfo personInfo) {int result = 0;Connection conn = null;PreparedStatement pstmt = null;try {conn = DBUtil.getConnection();String sql = "select * from PersonInfo where state = 1 and mail = ? and password = ?";pstmt = conn.prepareStatement(sql);pstmt.setString(1, personInfo.getMail());pstmt.setString(2, personInfo.getPassword());result = pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(null, pstmt, conn);}return result;} }

關聯的DBUtil類代碼如下

package com.mail.util;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource;public class DBUtil {/*** 這里采用 JNDI(java命名和目錄接口)方式加載JDBC DataSource* 需要在Tomcat服務器context.xml中配置文件配置數據源* * @return*/public static Connection getConnection() {Connection con = null;try {Context context = new InitialContext();DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/oracle");// 引用數據源con = dataSource.getConnection();} catch (Exception e) {e.printStackTrace();}return con;}/*** 關閉資源* * @param rs* 要關閉的結果集* @param pstmt* 要關閉的預編譯塊* @param con* 要關閉的連接*/public static void close(ResultSet rs, PreparedStatement pstmt, Connection con) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (pstmt != null) {try {pstmt.close();} catch (SQLException e) {e.printStackTrace();}}if (con != null) {try {con.close();} catch (SQLException e) {e.printStackTrace();}}} }

MailUtil代碼如下,(注意:這里需要填寫你提前準備的發件人郵箱和授權碼

package com.mail.util;import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.util.MailSSLSocketFactory;public class MailUtil {/*** 發送郵件的方法: 發送一封激活郵件* @param mail 收件人郵箱* @param actcode 收件人激活碼*/public static void sendMail(String mail,String actcode) {// 1.創建連接對象javax.mail.Session// 2.創建郵件對象 javax.mail.MessageString from = "21567565@qq.com";// 發件人電子郵箱String host = "smtp.qq.com"; // 指定發送郵件的主機smtp.qq.com(QQ)|smtp.163.com(網易)final String authorizationCode = "spxxanqcdoiqbhjh"; //授權碼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("21567565@qq.com",authorizationCode); // 發件人郵箱賬號、授權碼}});// 2.創建郵件對象Message message = new MimeMessage(session);// 2.1設置發件人message.setFrom(new InternetAddress(from));// 2.2設置接收人message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));// 2.3設置郵件主題message.setSubject("賬號激活");// 2.4設置郵件內容String content = "<html><head></head><body><h1>請點擊以下鏈接激活注冊賬號</h1><h3><a href='http://localhost:8080/RegisterDemo/ActiveServlet?code="+ actcode + "'>http://localhost:8080/javamail/active?actcode=" + actcode+ "</href></h3></body></html>";message.setContent(content, "text/html;charset=UTF-8");// 3.發送郵件Transport.send(message);System.out.println("激活郵件成功發送!");} catch (Exception e) {e.printStackTrace();}} }

6.注冊用戶登錄郵箱點擊激活鏈接,鏈接攜帶的激活碼會提交到ActiveServlet類進行激活,ActiveServlet類代碼如下

package com.mail.servlet;import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import com.mail.business.PersonInfoBusiness;/*** Servlet implementation class ActiveServlet*/ @WebServlet("/ActiveServlet") public class ActiveServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");String actcode = request.getParameter("actcode"); // 獲取注冊激活碼HttpSession session = request.getSession(); // 獲取存入session的激活碼String sessionActcode = session.getAttribute("actcode").toString();if (actcode.equals(sessionActcode)) { // 激活碼匹配PersonInfoBusiness personInfoBusiness = new PersonInfoBusiness();int result = personInfoBusiness.active(actcode);//激活賬號if(result == 1){request.getRequestDispatcher("/login.jsp").forward(request, response);}else{request.setAttribute("msg", "激活失敗!");request.getRequestDispatcher("/result.jsp").forward(request, response);}} else {request.setAttribute("msg", "激活碼不匹配,激活失敗!");request.getRequestDispatcher("/result.jsp").forward(request, response);}}}

?

7.ActiveServlet類會傳遞激活碼給業務層?PersonInfoBusiness進行激活操作,PersonInfoBusiness調用PersonInfoDao 改變賬號狀態激活賬號,然后ActiveServlet會自動跳轉到登錄界面login.jsp 。login.jsp代碼如下

<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>登錄</title> </head> <body> <h2>登錄頁面</h2> <hr/> <form method="POST" action="login"> <table><tr><td><label for="mail">郵箱:</label></td><td><input type="email" name="mail" id="mail"/></td></tr><tr><td><label for="password">密碼:</label></td><td><input type="password" name="password" id="password" /></td></tr><tr><td colspan="2"><input type="submit" value="登錄" /></td></tr> </table> </form> </body> </html>

8.登錄界面提交登錄信息 到LoginServlet登錄驗證??LoginServlet類代碼如下

package com.mail.servlet;import java.io.IOException; import java.util.UUID;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import com.mail.business.PersonInfoBusiness; import com.mail.pojo.PersonInfo;public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");String mail = request.getParameter("mail");String password = request.getParameter("password");PersonInfo personInfo = new PersonInfo();personInfo.setMail(mail);personInfo.setPassword(password);personInfo.setState(0);personInfo.setActcode(UUID.randomUUID().toString());// 生成唯一激活碼// 把激活碼存進sessionHttpSession session = request.getSession();session.setAttribute("actcode", personInfo.getActcode());PersonInfoBusiness personInfoBusiness = new PersonInfoBusiness();if (personInfoBusiness.login(personInfo) == 1) {request.setAttribute("msg", "登錄成功!");} else {request.setAttribute("msg", "登陸失敗!");}request.getRequestDispatcher("/result.jsp").forward(request, response);}}

9.顯示提示信息的頁面 result.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>結果頁</title> </head> <body>${msg} </body> </html>

三,運行結果

注冊界面:

提交信息后,提示信息如下:

看一下數據庫中數據信息:

登陸到976342421@qq.com 的郵箱查看激活郵件

復制激活鏈接,在新標簽頁打開,可以看到已跳轉到登錄頁面

此時再查看數據庫中數據狀態 賬號已激活

點擊登錄:

OK,項目完成!

總結

以上是生活随笔為你收集整理的java实现邮箱激活注册账号完整案例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。