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;
	}

	@Override
	public 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;

	@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 {
		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());// 生成唯一激活码
		// 把激活码存进session
		HttpSession 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.Message
		String 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;

	@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 {
		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());// 生成唯一激活码
		// 把激活码存进session
		HttpSession 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,项目完成!

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赴前尘

喜欢我的文章?请我喝杯咖啡吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值