工具类EmailUtil

public class EmailUtil {
    public static void send(String recipient, String subject, String content) {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");//开启协议
        props.setProperty("mail.smtp.host", "smtp.qq.com");//主机名
        props.setProperty("mail.smtp.auth", "true");//是否开启权限控制
        props.setProperty("mail.debug", "true");//true表示在发送邮件时会在控制台上打印发送时的信息

        //Session表示程序到邮件服务器之间的一次会话
        Session session = Session.getInstance(props);
        Message msg = new MimeMessage(session);//邮件对象
        try {
            msg.setFrom(new InternetAddress("369950806@qq.com"));//发送人
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));//收件人
            msg.setSubject(subject);//主题
            msg.setText(content);//正文

            Transport tran = session.getTransport();
            tran.connect("369950806", "ajhyxkqvapmzbggi");//此处不是QQ的密码,是开启POP3/SMTP时生成的authorization code
            tran.sendMessage(msg, msg.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
        @Override
    public User login(User user) throws SQLException {
        User userTemp = User.builder().username(user.getUsername()).build();
        //查询出指定名称的用户是否存在
        List<User> users = userDao.selectUserByCondition(userTemp);
        if (users.size() <= 0) {
            throw new RuntimeException("用户名不存在");
        }
        User userInDB = users.get(0);
        //比较加密后的密码是否一致
        if (MD5Util.encode(user.getPassword(), userInDB.getSalt()).equals(userInDB.getPassword())) {
            return userInDB;
        } else {
            throw new RuntimeException("密码不正确");
        }
    }
}

UserServiceImpl

UserServiceImpl中实现用户注册成功时,发送激活邮件功能。

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public void regist(User user) throws SQLException {
        //保存用户信息到数据库
        int insertUserRes = userDao.insertUser(user);
        if (insertUserRes >= 1) {
            //3.发送激活码到邮箱
            String subject = "来自微风商城的激活邮箱";
            String content = "点击如下连接激活账户,如果不能点击请复制到浏览器地址栏访问:http://www.wego.com/userServlet?op=active&code=检验码";
            EmailUtil.send(user.getEmail(), subject, content);
        } else {
            throw new RuntimeException("用户注册失败");
        }
    }

邮箱激活

@WebServlet(urlPatterns = "/userServlet")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("op");
        switch (op) {
            case "regist":
                try {
                    regist(request, response);
                } catch (InvocationTargetException | IllegalAccessException | SQLException e) {
                    e.printStackTrace();
                }
                break;
            case "login":
                try {
                    login(request,response);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    private void login(HttpServletRequest request,HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, SQLException, ServletException, IOException {
        //获取用户名和密码
        User user = new User();
        BeanUtils.populate(user, request.getParameterMap());
        user = userService.login(user);
        if(user == null){
            request.setAttribute("msg", "用户名或密码不正确!");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        // 检查用户激活状态
        if(user.getStatus() == 0){
            request.setAttribute("msg", "用户尚未激活,请到邮箱中进行激活!");
            request.getRequestDispatcher(request.getContextPath()+"/login.jsp").forward(request, response);
            return;
        }
        request.getSession().setAttribute("user",user);//将用户信息添加到Session中
        //重定向到主页
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

    /**
     * 用户注册
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IllegalAccessException, SQLException {
        //1.校验验证码
        String verifyCode = request.getParameter("verifyCode");
        String verifyCode0 = request.getSession().getAttribute("verifyCode").toString();
        if (verifyCode == null || verifyCode0 == null || !verifyCode.equalsIgnoreCase(verifyCode0)) {
            request.setAttribute("msg", "验证码不正确!");
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            return;
        }
        //2.封装校验数据
        User user = new User();
        BeanUtils.populate(user, request.getParameterMap());

        //3.调用Service注册用户
        userService.regist(user);

        //4.回到主页
        response.getWriter().write("注册成功,请打开注册邮箱在5分钟内进行激活...");
        response.setHeader("Refresh", "5;url=index.jsp");
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String op = request.getParameter("op");
        switch (op) {
            case "active":// 激活用户
                try {
                    activeCode(request, response);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
    private void activeCode(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        //1获取激活码
        String code = request.getParameter("code");
        String activeCode = Base64Util.decode(code);//MD5加密后的
        //2调用Service方法激活
        User user = userService.activeUser(activeCode);
        //3登录用户
        request.getSession().setAttribute("user", user);
        //4激活成功,5s后进入首页
        response.getWriter().write("恭喜您激活成功,3秒后回到主页....");
        response.setHeader("Refresh", "3;url=/index.jsp");
    }
}