spring+mybatis实现注册通过邮箱发送激活码注册用户

       

网站用户注册:

        主要实现如下两个功能:

1、用户在网站上注册完成后给用户发一封邮件。

2、用户通过邮件激活后才可以登录。

思路:

首先需要一个思路:

        用户在前台点击注册,向controller提交请求,把用户提交过来的信息封装成一个user(需要的信息有name,pwd,email这3个是用户填写的,我们帮用户生成的是id和一个邮箱激活链接地址的唯一标识码acode,还要一个用来识别用户是否已经点击链接的变量active)。 如果用户点击了链接后,我们会将用户的状态修改为true【对应的“”1”】,当我们登入时,会根据返会的actived状态,来判断用户是否已经激活了账户,若未激活,则登录不进去,否则,则可以;

        并且不能使用该邮箱重复注册用户,所以每次注册用户时,都会先通过邮箱查询该邮箱是否已经注册过了,没有,则可以注册,否则不行。

        用户点了激活链接后,再自动跳转到登录页面!

1:.POM.xml中导入javaxmail需要的依赖

2:controller类

package com.chinasofti.controller;

import com.chinasofti.pojo.User;

import com.chinasofti.service.UserService;

import com.chinasofti.util.EmailUtils;

import com.chinasofti.util.GenerateLinkUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import java.io.IOException;

import java.util.UUID;

@Controller

@RequestMapping("email")

public class UserController {

    @Autowired

    private UserService userService;

    @RequestMapping("toregist")

    public String toemail() {

        return "regist";

    }

@RequestMapping("login")

public  String login(){

        return "login";

}

    @RequestMapping("/regist")

    public void regist(User user, HttpSession httpSession, HttpServletResponse response) {

        user.setActivated(false);  //刚注册默认是没有激活状态

        user.setCodeUrl(UUID.randomUUID().toString());

        //注册用户

        User user1=userService.findUserByEmail(user.getEmail());

        if (user1==null) {

            userService.saveUser(user);

        } else {

            throw new RuntimeException("该邮箱已注册");

        }

        //查看是否注册成功,为实体类User的id赋值

        User findUser = userService.findUserByEmail(user.getEmail());

        if (findUser != null) {

            user.setId(findUser.getId());

        } else {

            throw new RuntimeException("注册用户失败");

        }

        //注册成功后,发送账户激活链接

        httpSession.setAttribute("user", user);

        EmailUtils.sendAccountActivateEmail(user);

        try {

            response.setContentType("text/html;charset=utf-8");

            response.getWriter().write("激活邮件已经发送,请注意提醒查收");

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    @RequestMapping("/activate")

    public void activate(String id, String checkCode, HttpServletResponse response) {

        int idInt = Integer.parseInt(id);

        //根据用户id查找用户

        User user = userService.findUserById(idInt);

        //验证无误,状态更改为1,即激活

        if (GenerateLinkUtils.verifyCheckcode(user, checkCode)) {

            //修改状态

            int activated = 1;

            userService.updateActivated(activated, idInt);

            user.setActivated(true);

            try {

                response.setContentType("text/html;charset=utf-8");

                response.getWriter().write("恭喜,激活成功!");

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}

3:service类

package com.chinasofti.service;

import com.chinasofti.dao.UserDao;

import com.chinasofti.pojo.User;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service

public class UserService {

    @Autowired

    private UserDao userDao;

    public void saveUser(User user) {

        userDao.saveUser(user);

    }

    public User findUserByEmail(String email) {

        return  userDao.findUserByEmail(email);

       

    }

    public User findUserById(int idInt) {

        return  userDao.findUserById(idInt);

    }

    public void updateActivated(int activated, int idInt) {

        userDao.updateActivated(activated,idInt);

    }

}

4:dao层

package com.chinasofti.dao;

import com.chinasofti.pojo.User;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

@Repository

public class UserDao {

    @Autowired

    private UserMapper userMapper;

    public User findUserByEmail(String email) {

        return  userMapper.findUserByEmail(email);

    }

    public User findUserById(int idInt) {

        return  userMapper.findUserById(idInt);

    }

    public void saveUser(User user) {

        userMapper.saveUser(user);

    }

    public void updateActivated(int activated, int idInt) {

        userMapper.updateActivated(activated,idInt);

    }

}

5:register.jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"

        pageEncoding="utf-8"%>

    注册

   

       

       

       

       

   

用户名:
密码:
邮箱:

6:User实体类

package com.chinasofti.pojo;

public class User {

    private int id;

    private String username;

    private String password;

    private String email;

    private boolean activated;  //账号状态

    private String codeUrl;      //激活链接中的随机码

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

    public boolean isActivated() {

        return activated;

    }

    public void setActivated(boolean activated) {

        this.activated = activated;

    }

    public String getCodeUrl() {

        return codeUrl;

    }

    public void setCodeUrl(String codeUrl) {

        this.codeUrl = codeUrl;

    }

}

  7:mapper.xml文件

   

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


   

   

       

       

       

       

       

       

   

   

        INSERT  INTO users VALUES (#{id},#{username},#{password},#{email},#{activated},#{codeUrl})

   

   

   

   

        UPDATE users SET activated=#{activated} WHERE  id=#{idInt}

   

   

8:EmailUtils工具类:

package com.chinasofti.util;

import com.chinasofti.pojo.User;

import java.util.Date;

import java.util.Properties;

import javax.mail.Authenticator;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMessage.RecipientType;

public class EmailUtils {

    private static final String FROM = "[email protected]";

    public static void sendAccountActivateEmail(User user) {

        Session session = getSession();

        MimeMessage message = new MimeMessage(session);

        try {

            message.setSubject("这是一封激活账号的邮件");

            message.setSentDate(new Date());

            //setFrom 表示用哪个邮箱发送邮件

            message.setFrom(new InternetAddress(FROM));

            /**

            * RecipientType.TO||BCC||CC

            *    TO表示主要接收人

            *    BCC表示秘密抄送人

            *    CC表示抄送人

            * InternetAddress  接收者的邮箱地址

            */

            message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));

            message.setContent(""+user.getUsername()+"先生/女士您好,请点击此链接激活账号"+GenerateLinkUtils.generateActivateLink(user)

        +"","text/html;charset=utf-8");

//            message.setContent("" + user.getUsername() + "先生/女士您好,请点击此链接激活账号" + GenerateLinkUtils.generateActivateLink(user)

//                    + "", "text/html;charset=utf-8");

            Transport.send(message);

        } catch (MessagingException e) {

            e.printStackTrace();

        }

    }

    public static Session getSession() {

        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");//指定发送的邮箱的邮箱协议

        props.setProperty("mail.smtp.host", "smtp.163.com");//指定SMTP服务器

        props.setProperty("mail.smtp.port", "25");  //smtp是发信邮件服务器,端口是25

        props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP验证

        Session session = Session.getInstance(props, new Authenticator() {

            @Override

            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(FROM, "98liang032");

            }

        });

        return session;

    }

}

9:GenerateLinkUtils:

package com.chinasofti.util;

import com.chinasofti.pojo.User;

import java.util.Date;

import java.util.Properties;

import javax.mail.Authenticator;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMessage.RecipientType;

public class EmailUtils {

    private static final String FROM = "**********@163.com";

    public static void sendAccountActivateEmail(User user) {

        Session session = getSession();

        MimeMessage message = new MimeMessage(session);

        try {

            message.setSubject("这是一封激活账号的邮件");

            message.setSentDate(new Date());

            //setFrom 表示用哪个邮箱发送邮件

            message.setFrom(new InternetAddress(FROM));

            /**

            * RecipientType.TO||BCC||CC

            *    TO表示主要接收人

            *    BCC表示秘密抄送人

            *    CC表示抄送人

            * InternetAddress  接收者的邮箱地址

            */

            message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));

            message.setContent(""+user.getUsername()+"先生/女士您好,请点击此链接激活账号"+GenerateLinkUtils.generateActivateLink(user)

        +"","text/html;charset=utf-8");

//            message.setContent("" + user.getUsername() + "先生/女士您好,请点击此链接激活账号" + GenerateLinkUtils.generateActivateLink(user)

//                    + "", "text/html;charset=utf-8");

            Transport.send(message);

        } catch (MessagingException e) {

            e.printStackTrace();

        }

    }

    public static Session getSession() {

        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");//指定发送的邮箱的邮箱协议

        props.setProperty("mail.smtp.host", "smtp.163.com");//指定SMTP服务器

        props.setProperty("mail.smtp.port", "25");  //smtp是发信邮件服务器,端口是25

        props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP验证

        Session session = Session.getInstance(props, new Authenticator() {

            @Override

            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(FROM, "***********");//该地方是填写客户端的授权码

            }

        });

        return session;

    }

}

        以上代码本人已亲测过,能够正常访问,代码较多,请耐心分析,解读!!!!

你可能感兴趣的:(spring+mybatis实现注册通过邮箱发送激活码注册用户)