servlet邮箱激活验证实例含代码

 也有很多人本来有机会的,他们都拒绝了,不想让自己太累,太麻烦。或者中途被情绪所左右,半途而废了。 成长是有代价的,同样悠闲也是有代价的。

 

流程:

  1. 用户填写相关信息,点击注册按钮
  2. 系统先将用户记录保存到数据库中,其中用户状态为未激活
  3. 系统发送一封邮件并通知用户去验证
  4. 用户登录邮箱并点击激活链接
  5. 系统将用户状态更改为已激活并通知用户注册成功

相关知识点

 

1、在邮箱设置中将下图的服务器开启,本案例使用的是QQ邮箱为发送邮箱。

点击生成授权码,得到的授权码yzufrxhatukfbcig拷贝到MailUtil.java中的session对象中

   // 1.获取默认session对象

Session session = Session.getDefaultInstance(properties, new Authenticator() {

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("769470499@qq.com", "yzufrxhatukfbcig"); // 发件人邮箱账号、授权码

}

});

2、创建maven工程 ,并且引入依赖

4、创建数据库mysql

create table `user`(

    id int(11) primary key auto_increment comment '用户id',

    username varchar(255) not null comment '用户名',

    email varchar(255) not null comment '用户邮箱',

    password varchar(255) not null comment '用户密码',

    state int(1) not null default 0 comment '用户激活状态:0表示未激活,1表示激活',

    code varchar(255) not null comment '激活码'

)engine=InnoDB default charset=utf8;

 

 

5、创建一个jssp页面作为demo验证

6、首先是,用户提交注册信息后,相应的servlet会将相关信息传给service层去处理,在service中需要做的就是讲记录保存到数据库中(ji调用dao层),然后再给用户发送一封邮件,UserServiceImpl代码如下:

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;

}

7、c3p0最简单的配置如下:

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>

    <named-config name="mysql">

        <property name="driverClass">com.mysql.jdbc.Driver</property>

        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test1?useSSL=false</property>

        <property name="user">root</property>

        <property name="password">123456</property>

        <!-- 初始化时一个连接池尝试获得的连接数量,默认是3,大小应该在maxPoolSize和minPoolSize之间 -->

        <property name="initialPoolSize">5</property>

        <!-- 一个连接最大空闲时间(单位是秒),0意味着连接不会过时 -->

        <property name="maxIdleTime">30</property>

        <!-- 任何指定时间的最大连接数量 ,默认值是15 -->

        <property name="maxPoolSize">20</property>

        <!-- 任何指定时间的最小连接数量 ,默认值是3 -->

        <property name="minPoolSize">5</property>

    </named-config>

</c3p0-config>

8、提供一个工具类DBUtil以获取,释放连接

 

public class DBUtil {

private static ComboPooledDataSource cpds=null;

static{

    cpds=new ComboPooledDataSource("mysql");

}

public static Connection getConnection(){

    Connection connection=null;

    try {

        connection = cpds.getConnection();

    } catch (SQLException e) {

        e.printStackTrace();

    }

    return connection;

}

public static void close(Connection conn,PreparedStatement pstmt,ResultSet rs){

    try {

        if(rs!=null){

            rs.close();

        }

        if(pstmt!=null){

            pstmt.close();

        }

        if(rs!=null){

            rs.close();

        }

    } catch (SQLException e) {

        e.printStackTrace();

    }

     

}

}

 

9、使用JavaMail发送邮件

  1. 创建连接对象javax.mail.Session
  2. 创建邮件对象 javax.mail.Message
  3. 发送邮件

MailUtil代码如下:

 

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 = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost:8080/RegisterDemo/ActiveServlet?code="

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

                    + "</href></h3></body></html>";

            message.setContent(content, "text/html;charset=UTF-8");

            // 3.发送邮件

            Transport.send(message);

            System.out.println("邮件成功发送!");

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

代码

原文地址:https://www.cnblogs.com/gaoqiaoliangjie/p/9269721.html