JavaWeb网上图书商城完整项目--day02-8.提交注册表单功能之dao、service实现

1、发送邮件

发送邮件的时候的参数我们都写在了配置文件中,配置文件放在src目录下,可以使用类加载器进行加载该数据

//向注册的用户发送邮件
     //1读取配置文件
      Properties properties = new Properties();
      try {
        properties.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
    } catch (IOException e1) {
        throw new RuntimeException(e.getMessage());
    }

<a href="http://localhost:8080/goods/UserServlet?method=activation&activationCode={0}",这里有一个占位符{0},第二个占位符对应应该是{1},我们可以使用实际的值替换对应的占位符。

这里我们定义了两个占位符,其中的数字对应于传入的参数数组中的索引,{0}占位符被第一个参数替换,{1}占位符被第二个参数替换,依此类推。

 String content = properties.getProperty("content");
        //替换占位符
        MessageFormat.format(content, user.getActivationCode());//替换占位符
 

收到邮件之后点击href,交给UserServlet的activation方法进行处理,并且把activationCode激活码携带过来。此激活码会和保存到数据库中的激活码进行比较

我们来看UserServlet的代码:

package com.weiyuan.goods.user.web.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 com.weiyuan.goods.user.service.UserService;

import cn.itcast.servlet.BaseServlet;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet{
    private static final long serialVersionUID = 1L;
    private UserService service = new UserService();
    /*
     * 用户注册页面使用ajax校验/*
     * 用户注册页面使用ajax校验用户名会调用该方法
     * *会调用该方法
     * */
    public String validateLoginname(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //首先获得用户上传的用户名
        String loginName = request.getParameter("loginname");
        boolean  flag = service.ajaxValidateLoginName(loginName);
        response.getWriter().print(flag);
        return null;
    }
    /*
     * 用户注册页面使用ajax校验邮箱会调用该方法
     * */
    public String validateEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
       //获得用户上传的emai
    
        String email = request.getParameter("email");
        System.out.println("validateEmail is called"+email);
        boolean  flag = service.ajaxValidateEmail(email);
        response.getWriter().print(flag);
        return null;
    }
    
    /*
     * 用户注册页面使用ajax校验验证码会调用该方法
     * */
    public String validateVerifyCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
         //获得用户上传的verfycode
        String verifyCode  = request.getParameter("verifyCode");
        //获得session中保存的验证码
        String sessionCode = (String) request.getSession().getAttribute("vCode");
        //二者进行比较看是否相等
        System.out.println("validateVerifyCode is called"+verifyCode+":"+sessionCode);
        boolean  flag = sessionCode.equalsIgnoreCase(verifyCode);
        response.getWriter().print(flag);
        return null;
    }
    
    /*
     * 当用户注册的时候会调用该方法
     * 
     * */
    public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("registis called");
        return null;
    }
    
    /*
     * 当用户点击邮件的时候会调用该方法,会把邮件携带的激活码传递过来
     * 
     * */


}

我们来看看业务层的代码:

package com.weiyuan.goods.user.service;

import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.management.RuntimeErrorException;

import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;

import com.weiyuan.goods.user.dao.UserDao;
import com.weiyuan.goods.user.domian.User;

public class UserService {

 private UserDao dao = new UserDao();    
    
 
 public boolean ajaxValidateLoginName(String loginName) {
     
     try {
        return dao.ajaxValidateLoginName(loginName);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        throw new RuntimeException(e.getMessage());
    }
     
 }
 
public boolean ajaxValidateEmail(String email) {
     
     try {
        return dao.ajaxValidateEmail(email);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        throw new RuntimeException(e.getMessage());
    }
     
 }

//添加注册的用户
public void addUser(User user){
    //添加用户的uuid
    user.setUid(CommonUtils.uuid());
    //添加用户的激活码
    String activationCode = CommonUtils.uuid()+CommonUtils.uuid();
    user.setActivationCode(activationCode);
    //当前处于未激活的状态
    user.setStatus(0);//0表示未激活
    
    try {
        dao.addUser(user);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        throw new RuntimeException(e.getMessage());
    }
    
    //向注册的用户发送邮件
     //1读取配置文件
      Properties properties = new Properties();
      try {
        properties.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
    } catch (IOException e1) {
        throw new RuntimeException(e1.getMessage());
    }
    
    
     String host = properties.getProperty("host"); //qq邮箱发送邮件的地址,端口465或者587
        //qq接受邮件服务器的地址是pop.qq.com,端口995
        String username=properties.getProperty("username"); //登陆服务器的账号
        String password=properties.getProperty("password");//这里不是客户端登陆的密码,而是授权密码一定要注意
        Session session = MailUtils.createSession(host, username, password);
        //发送邮件
        String from = properties.getProperty("from");//发件人
        String to = user.getEmail();//收件人
        String title = properties.getProperty("subject");
        String content = properties.getProperty("content");
        //替换占位符
        MessageFormat.format(content, user.getActivationCode());//替换占位符
        Mail mail = new Mail(from,to,title,content);
        try {
            MailUtils.send(session, mail);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } 
    
    
    
}

}

 我们来看看数据库的代码:

package com.weiyuan.goods.user.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.weiyuan.goods.user.domian.User;

import cn.itcast.jdbc.TxQueryRunner;

public class UserDao {

     //操作数据库
    private TxQueryRunner qr = new TxQueryRunner();
    
    
    /***
     * 查询用户名是否存在
     * @throws SQLException 
     */
    public boolean ajaxValidateLoginName(String loginName) throws SQLException{
        //获得满足记录的数目是对象,返回一个整数,整数是单行单列使用ScalarHandler
        String sql ="select count(*) from t_user where loginname=?";
        Number num = (Number) qr.query(sql, new ScalarHandler(),loginName);
        int count = num.intValue();

        if(count>0){
            return true;
        }
        return false;
    }
    
    /***
     * 查询邮箱是否存在
     * @throws SQLException 
     */
    public boolean ajaxValidateEmail(String email) throws SQLException{
        //获得满足记录的数目是对象,返回一个整数,整数是单行单列使用ScalarHandler
        String sql ="select count(*) from t_user where email=?";
        Number num = (Number) qr.query(sql, new ScalarHandler(),email);
        int count = num.intValue();
        System.out.println("count="+count);
        if(count>0){
            return true;
        }
        return false;
    }
    
    /***
     * 添加注册的用户
     * @throws SQLException 
     */
    public void addUser(User user) throws SQLException{
        //获得满足记录的数目是对象,返回一个整数,整数是单行单列使用ScalarHandler
        String sql ="insert into  t_user values (?,?,?,?,?,?)";
        Object[] params = {user.getUid(),user.getLoginname(),user.getLoginpass(),
                user.getEmail(),user.getStatus(),user.getActivationCode()};
        qr.update(sql, params);
    }
    
}
原文地址:https://www.cnblogs.com/kebibuluan/p/6841211.html