javaMail登录并实现邮箱激活功能

项目准备的工具和jar包请自行下载

链接: https://pan.baidu.com/s/1wYOPwscRkUlwWmfcxe_Elg 提取码: yi7q 复制这段内容后打开百度网盘手机App,操作更方便哦

 

1.新建一个Dynamic Web Project项目,里面加入要用到的jar包,整体的框架如图所示:

 

2.新建一个数据库,里面新建一张表,表结构如图所示:

 

3.用易邮邮件服务器新建几个账号,整体框架如图所示:

 

4.用foxmail新建几个邮箱,整体框架如下所示:

 

5.UserDao.java代码:

 

[java] view plain copy  print?

  1. package dao;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import domain.User;  
  6.   
  7. public interface UserDao {  
  8.   
  9.     void regist(User user) throws SQLException;  
  10.   
  11.     User findByCode(String code) throws SQLException;  
  12.   
  13.     void update(User user) throws SQLException;  
  14.   
  15. }  


6.UserDaoImpl.java代码:

 

 

[java] view plain copy  print?

  1. package dao;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import org.apache.commons.dbutils.QueryRunner;  
  6. import org.apache.commons.dbutils.handlers.BeanHandler;  
  7.   
  8. import utils.JdbcUtils;  
  9. import domain.User;  
  10.   
  11. public class UserDaoImpl implements UserDao {  
  12.   
  13.     @Override  
  14.     public void regist(User user) throws SQLException {  
  15.         QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());  
  16.         String sql = "insert into user values (?,?,?,?,?,?,?)";  
  17.         Object[] params = { user.getUid(), user.getUsername(),  
  18.                 user.getPassword(), user.getNickname(), user.getEmail(),  
  19.                 user.getState(), user.getCode() };  
  20.         queryRunner.update(sql, params);  
  21.     }  
  22.   
  23.     @Override  
  24.     public User findByCode(String code) throws SQLException {  
  25.         QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());  
  26.         String sql = "select * from user where code = ?";  
  27.         User user = queryRunner.query(sql, new BeanHandler<User>(User.class),  
  28.                 code);  
  29.         return user;  
  30.     }  
  31.   
  32.     @Override  
  33.     public void update(User user) throws SQLException {  
  34.         QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());  
  35.         String sql = "update user set username=?,password=?,nickname=?,email=?,state=?,code=? where uid=?";  
  36.         Object[] param = { user.getUsername(), user.getPassword(),  
  37.                 user.getNickname(), user.getEmail(), user.getState(),  
  38.                 user.getCode(), user.getUid() };  
  39.         queryRunner.update(sql, param);  
  40.     }  
  41.   
  42. }  


7.User.java代码:

 

 

[java] view plain copy  print?

  1. package domain;  
  2.   
  3. public class User {  
  4.   
  5.     private Integer uid;  
  6.     private String username;  
  7.     private String password;  
  8.     private String nickname;  
  9.     private String email;  
  10.     private Integer state;  
  11.     private String code;  
  12.   
  13.     public Integer getUid() {  
  14.         return uid;  
  15.     }  
  16.   
  17.     public void setUid(Integer uid) {  
  18.         this.uid = uid;  
  19.     }  
  20.   
  21.     public String getUsername() {  
  22.         return username;  
  23.     }  
  24.   
  25.     public void setUsername(String username) {  
  26.         this.username = username;  
  27.     }  
  28.   
  29.     public String getPassword() {  
  30.         return password;  
  31.     }  
  32.   
  33.     public void setPassword(String password) {  
  34.         this.password = password;  
  35.     }  
  36.   
  37.     public String getNickname() {  
  38.         return nickname;  
  39.     }  
  40.   
  41.     public void setNickname(String nickname) {  
  42.         this.nickname = nickname;  
  43.     }  
  44.   
  45.     public String getEmail() {  
  46.         return email;  
  47.     }  
  48.   
  49.     public void setEmail(String email) {  
  50.         this.email = email;  
  51.     }  
  52.   
  53.     public Integer getState() {  
  54.         return state;  
  55.     }  
  56.   
  57.     public void setState(Integer state) {  
  58.         this.state = state;  
  59.     }  
  60.   
  61.     public String getCode() {  
  62.         return code;  
  63.     }  
  64.   
  65.     public void setCode(String code) {  
  66.         this.code = code;  
  67.     }  
  68.   
  69. }  


8.UserService.java代码:

 

 

[java] view plain copy  print?

  1. package service;  
  2.   
  3. import domain.User;  
  4.   
  5. public interface UserService {  
  6.   
  7.     void regist(User user) throws Exception;  
  8.   
  9.     User findByCode(String code) throws Exception;  
  10.   
  11.     void update(User user) throws Exception;  
  12.   
  13. }  


9.UserServiceImpl.java代码:

 

 

[java] view plain copy  print?

  1. package service;  
  2.   
  3. import utils.MailUtils;  
  4. import dao.UserDao;  
  5. import dao.UserDaoImpl;  
  6. import domain.User;  
  7.   
  8. public class UserServiceImpl implements UserService {  
  9.   
  10.     @Override  
  11.     public void regist(User user) throws Exception {  
  12.         UserDao userDao = new UserDaoImpl();  
  13.         userDao.regist(user);  
  14.         MailUtils.sendMail(user.getEmail(), user.getCode());  
  15.     }  
  16.   
  17.     @Override  
  18.     public User findByCode(String code) throws Exception {  
  19.         UserDao userDao=new UserDaoImpl();  
  20.         return userDao.findByCode(code);  
  21.     }  
  22.   
  23.     @Override  
  24.     public void update(User user) throws Exception {  
  25.         UserDao userDao=new UserDaoImpl();  
  26.         userDao.update(user);  
  27.     }  
  28.   
  29. }  


10.ActiveServlet.java代码:

 

 

[java] view plain copy  print?

  1. package servlet;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.annotation.WebServlet;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import domain.User;  
  12. import service.UserService;  
  13. import service.UserServiceImpl;  
  14.   
  15. @WebServlet("/ActiveServlet")  
  16. public class ActiveServlet extends HttpServlet {  
  17.     private static final long serialVersionUID = 1L;  
  18.   
  19.     protected void doGet(HttpServletRequest request,  
  20.             HttpServletResponse response) throws ServletException, IOException {  
  21.         doPost(request, response);  
  22.     }  
  23.   
  24.     protected void doPost(HttpServletRequest request,  
  25.             HttpServletResponse response) throws ServletException, IOException {  
  26.         try {  
  27.             String code = request.getParameter("code");  
  28.             UserService userService = new UserServiceImpl();  
  29.             User user = userService.findByCode(code);  
  30.             if (user != null) {  
  31.                 user.setState(1);  
  32.                 user.setCode(null);  
  33.                 userService.update(user);  
  34.                 request.setAttribute("msg""您的已经激活成功!请去登录!");  
  35.             } else {  
  36.                 request.setAttribute("msg""您的激活码有误,请重新激活!");  
  37.             }  
  38.             request.getRequestDispatcher("/msg.jsp").forward(request, response);  
  39.         } catch (Exception e) {  
  40.             e.printStackTrace();  
  41.             throw new RuntimeException();  
  42.         }  
  43.     }  
  44.   
  45. }  


11.RegistServlet.java代码:

 

 

[java] view plain copy  print?

  1. package servlet;  
  2.   
  3. import java.io.IOException;  
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.HttpServlet;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import service.UserService;  
  10. import service.UserServiceImpl;  
  11. import utils.UUIDUtils;  
  12. import domain.User;  
  13.   
  14. public class RegistServlet extends HttpServlet {  
  15.   
  16.     private static final long serialVersionUID = 1L;  
  17.   
  18.     protected void doGet(HttpServletRequest request,  
  19.             HttpServletResponse response) throws ServletException, IOException {  
  20.         doPost(request, response);  
  21.     }  
  22.   
  23.     protected void doPost(HttpServletRequest request,  
  24.             HttpServletResponse response) throws ServletException, IOException {  
  25.         try {  
  26.             request.setCharacterEncoding("utf-8");  
  27.             String username = request.getParameter("username");  
  28.             String password = request.getParameter("password");  
  29.             String nickname = request.getParameter("nickname");  
  30.             String email = request.getParameter("email");  
  31.             User user = new User();  
  32.             user.setUsername(username);  
  33.             user.setPassword(password);  
  34.             user.setNickname(nickname);  
  35.             user.setEmail(email);  
  36.             user.setState(0);  
  37.             String code = UUIDUtils.getUUID() + UUIDUtils.getUUID();  
  38.             user.setCode(code);  
  39.             UserService userService = new UserServiceImpl();  
  40.             userService.regist(user);  
  41.             request.setAttribute("msg""您已经注册成功,请去邮箱激活!");  
  42.             request.getRequestDispatcher("/msg.jsp").forward(request, response);  
  43.         } catch (Exception e) {  
  44.             e.printStackTrace();  
  45.             throw new RuntimeException();  
  46.         }  
  47.     }  
  48.   
  49. }  


12.JdbcUtils.java代码:

 

 

[java] view plain copy  print?

  1. package utils;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5.   
  6. import javax.sql.DataSource;  
  7.   
  8. import com.mchange.v2.c3p0.ComboPooledDataSource;  
  9.   
  10. public class JdbcUtils {  
  11.   
  12.     private static DataSource ds = new ComboPooledDataSource();  
  13.     private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();  
  14.   
  15.     public static DataSource getDataSource() {  
  16.         return ds;  
  17.     }  
  18.   
  19.     public static Connection getConnection() throws SQLException {  
  20.         Connection con = tl.get();  
  21.         if (con != null)  
  22.             return con;  
  23.         return ds.getConnection();  
  24.     }  
  25.   
  26.     public static void beginTransaction() throws SQLException {  
  27.         Connection con = tl.get();  
  28.         if (con != null)  
  29.             throw new SQLException("已经开启了事务,不能重复开启!");  
  30.         con = ds.getConnection();  
  31.         con.setAutoCommit(false);  
  32.         tl.set(con);  
  33.     }  
  34.   
  35.     public static void commitTransaction() throws SQLException {  
  36.         Connection con = tl.get();  
  37.         if (con == null)  
  38.             throw new SQLException("没有事务不能提交!");  
  39.         con.commit();  
  40.         con.close();  
  41.         con = null;  
  42.         tl.remove();  
  43.     }  
  44.   
  45.     public static void rollbackTransaction() throws SQLException {  
  46.         Connection con = tl.get();  
  47.         if (con == null)  
  48.             throw new SQLException("没有事务不能回滚!");  
  49.         con.rollback();  
  50.         con.close();  
  51.         con = null;  
  52.         tl.remove();  
  53.     }  
  54.   
  55.     public static void releaseConnection(Connection connection)  
  56.             throws SQLException {  
  57.         Connection con = tl.get();  
  58.         if (connection != con) {  
  59.             if (connection != null && !connection.isClosed()) {  
  60.                 connection.close();  
  61.             }  
  62.         }  
  63.     }  
  64. }  


13.MailUtils.java代码:

 

 

[java] view plain copy  print?

  1. package utils;  
  2.   
  3. import java.util.Properties;  
  4.   
  5. import javax.mail.Authenticator;  
  6. import javax.mail.Message;  
  7. import javax.mail.Transport;  
  8. import javax.mail.Message.RecipientType;  
  9. import javax.mail.PasswordAuthentication;  
  10. import javax.mail.Session;  
  11. import javax.mail.internet.InternetAddress;  
  12. import javax.mail.internet.MimeMessage;  
  13.   
  14. public class MailUtils {  
  15.   
  16.     public static void sendMail(String to, String code) throws Exception {  
  17.         Properties properties = new Properties();  
  18.         Session session = Session.getInstance(properties, new Authenticator() {  
  19.             @Override  
  20.             protected PasswordAuthentication getPasswordAuthentication() {  
  21.                 return new PasswordAuthentication("service@store.com""root");  
  22.             }  
  23.         });  
  24.         Message message = new MimeMessage(session);  
  25.         message.setFrom(new InternetAddress("service@store.com"));  
  26.         message.setRecipient(RecipientType.TO, new InternetAddress(to));  
  27.         message.setSubject("来自XX网站的激活邮件");  
  28.         message.setContent(  
  29.                 "<h1>来自XX网站的激活邮件,点击</h1><h3><a href='http://localhost:8080/regist/ActiveServlet?code="  
  30.                         + code  
  31.                         + "'>http://localhost:8080/regist/ActiveServlet?code="  
  32.                         + code + "</a></h3>""text/html;charset=utf-8");  
  33.         Transport.send(message);  
  34.     }  
  35.   
  36. }  


14.UUIDUtils.java代码:

 

 

[java] view plain copy  print?

  1. package utils;  
  2.   
  3. import java.util.UUID;  
  4.   
  5. public class UUIDUtils {  
  6.   
  7.     public static String getUUID() {  
  8.         return UUID.randomUUID().toString().replace("-""");  
  9.     }  
  10.   
  11. }  


15.c3p0-config.xml代码:

 

 

[html] view plain copy  print?

  1. <c3p0-config>    
  2.     <default-config>    
  3.         <property name="jdbcUrl">jdbc:mysql://localhost:3306/regist_web?characterEncoding=utf-8</property>    
  4.         <property name="driverClass">com.mysql.jdbc.Driver</property>    
  5.         <property name="user">root</property>    
  6.         <property name="password">root</property>    
  7.     
  8.         <property name="checkoutTimeout">30000</property>    
  9.         <property name="idleConnectionTestPeriod">30</property>    
  10.         <property name="initialPoolSize">10</property>    
  11.         <property name="maxIdleTime">30</property>    
  12.         <property name="maxPoolSize">100</property>    
  13.         <property name="minPoolSize">10</property>    
  14.         <property name="maxStatements">200</property>    
  15.     </default-config>    
  16. </c3p0-config>    


16.web.xml代码:

 

 

[html] view plain copy  print?

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">  
  3.   <display-name>regist</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>index.html</welcome-file>  
  6.     <welcome-file>index.htm</welcome-file>  
  7.     <welcome-file>index.jsp</welcome-file>  
  8.     <welcome-file>default.html</welcome-file>  
  9.     <welcome-file>default.htm</welcome-file>  
  10.     <welcome-file>default.jsp</welcome-file>  
  11.   </welcome-file-list>  
  12.   <servlet>  
  13.     <servlet-name>RegistServlet</servlet-name>  
  14.     <servlet-class>servlet.RegistServlet</servlet-class>  
  15.   </servlet>  
  16.   <servlet-mapping>  
  17.     <servlet-name>RegistServlet</servlet-name>  
  18.     <url-pattern>/RegistServlet</url-pattern>  
  19.   </servlet-mapping>  
  20. </web-app>  


17.msg.jsp代码:

 

 

[html] view plain copy  print?

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Insert title here</title>  
  8. </head>  
  9. <body>  
  10.     <h1>${msg }</h1>  
  11. </body>  
  12. </html>  


18.regist.jsp代码:

 

 

[html] view plain copy  print?

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Insert title here</title>  
  8. </head>  
  9. <body>  
  10.     <h1>用户注册的界面</h1>  
  11.     <form action="RegistServlet" method="post">  
  12.         <table width="600" border="1">  
  13.             <tr>  
  14.                 <td>用户名:</td>  
  15.                 <td><input type="text" name="username"/></td>  
  16.             </tr>  
  17.             <tr>  
  18.                 <td>密码:</td>  
  19.                 <td><input type="password" name="password"/></td>  
  20.             </tr>  
  21.             <tr>  
  22.                 <td>昵称:</td>  
  23.                 <td><input type="text" name="nickname"/></td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td>邮箱:</td>  
  27.                 <td><input type="text" name="email"/></td>  
  28.             </tr>  
  29.             <tr>  
  30.                 <td colspan="2"><input type="submit" value="注册"/></td>  
  31.             </tr>  
  32.         </table>  
  33.     </form>  
  34. </body>  
  35. </html>  


19.在浏览器里面输入http://localhost:8080/regist/regist.jsp运行,输入user01和user02的信息,其中user01只是注册,不按照提示去邮件激活,而user02则根据提示去邮件激活,然后看看数据库里面的code和state的状态,比较一下两者的不同:

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值