Java 实现邮箱验证

1.Java实现用户注册,邮箱验证码激活的核心代码:

1.1 在RegisterServlet 用户注册类中

public class RegisterServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName=request.getParameter("username");
        String password=request.getParameter("password");
        String email=request.getParameter("email");
        System.out.println(userName+" "+password+" "+email);
        UserService userService=new UserServiceImpl();

        if(userService.doRegister(userName,password,email)){
            request.setAttribute("msg", "注册成功,请登录邮箱激活账号");
        }else{
            request.setAttribute("msg", "注册失败,请检查相关信息");
        }
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    }
}

1.2 在ActiveServlet 邮箱验证中:

public class ActiveServlet extends HttpServlet {

     private static final long serialVersionUID = 1L;

     @Override
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String code=request.getParameter("code");
          UserService userService=new UserServiceImpl();
          if(userService.activeUser(code)){
               request.getRequestDispatcher("/welcome.jsp").forward(request, response);
          }else{
               request.getRequestDispatcher("/fail.jsp").forward(request, response);
          }
     }
     @Override
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          this.doGet(request, response);
     }
}

1.3 在UserService中

public interface UserService {
     boolean doRegister(String userName, String password, String email);
     boolean activeUser(String code);
}

1.4 在UserServiceImpl中

public class UserServiceImpl implements UserService {

     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;
     }

     public boolean activeUser(String code) {
          UserDao userDao=new UserDaoImpl();
          if(userDao.activeUser(code)>0){
              return true;
          }else{
              return false;
          }
     }
}

1.5 在UserDao中

public interface UserDao {
     int save(User user);
     int activeUser(String code);
}

1.6 在UserDaoImpl中

public class UserDaoImpl implements UserDao{
     public int save(User user) {
          int num=0;
          try {
              Connection conn=DBUtil.getConnection();
              String sql ="insert into user(username,email,password,state,code) values(?,?,?,?,?)";
              PreparedStatement pstmt=conn.prepareStatement(sql);
              pstmt.setString(1, user.getUserName());
              pstmt.setString(2, user.getEmail());
              pstmt.setString(3, user.getPassword());
              pstmt.setInt(4, user.getState());
              pstmt.setString(5, user.getCode());
              num=pstmt.executeUpdate();
              DBUtil.close(conn,pstmt, null);
          } catch (SQLException e) {
              e.printStackTrace();
          }
          return num;
     }

     public int activeUser(String code) {
          int num=0;
          try {
              Connection conn=DBUtil.getConnection();
              String sql="update user set state=1 where code=?";
              PreparedStatement pstmt=conn.prepareStatement(sql);
              pstmt.setString(1, code);
              num=pstmt.executeUpdate();
              DBUtil.close(conn,pstmt,null);
          } catch (SQLException e) {
              e.printStackTrace();
          }
          return num;
     }
}

1.7 在CodeUtil中

public class CodeUtil {
     //生成唯一的激活码
     public static String generateUniqueCode(){
          return UUID.randomUUID().toString().replaceAll("-", "");
     }
}

1.8 在 MailUtils中

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();
          }
     }
}

1.9 在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();
          }

     }
}

1.10 所用到数据库表

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;

 

     PS:若想通过代码更好的理解Java发送邮件,请:https://github.com/luomingkui/RegisterDemo

 

2.Java实现用户登录邮箱验证项目的核心代码:

2.1 点击获取验证码,调用如下:

     在AdminUserController中

//获取验证码
@RequestMapping(value = "getVcode")
@ResponseBody
public Map<String, Object> getVcode(HttpServletRequest request) {
    String userName = request.getParameter("userName");
    Map<String , Object> map =new HashMap<String , Object>(4);
    String msg;
    try {
        String send=adminUserService.genSendVecode(userName);
        map.put("status", Constant.SUCCESS);
        map.put("msg", send);
        return map;
    } catch (Exception e) {
        if (e instanceof WlbException) {
            msg = e.getMessage();
        } else {
            msg = "管理系统异常,请稍候重试";
        }
        WlbManageLogger.e(">>>>>> loginIn action时异常,具体原因:%s", e.getLocalizedMessage()); 
        e.printStackTrace();
    }
    map.put("status", Constant.ERROR);
    map.put("msg", msg);
    return map;
}

2.2 在AdminUserService中:

@Service
public class AdminUserService {
    @Autowired
    private AdminUserDao adminUserDao;
    @Autowired
    private AdminAuthDao adminAuthDao;

    private static String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串

    private static long expireTime = 24 * 60 * 60 * 1000;

    public static String generateVcode(String cellphone) {
        StringBuilder tmp = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 6; i++) {
            tmp.append(getRandomString(rand.nextInt(36)));
        }
        return tmp.toString();
    }

    public static String getRandomString(int num){
        return String.valueOf(randString.charAt(num));
    }

    /**
     * 邮箱发送验证码
     * @param userEmail
     * @return
     */
    public String genSendVecode(String userEmail) {
        // 1. 校验邮箱是否正确
        // 2. 校验邮箱是否合法
        // 3. 生成验证码
        // 4. 将验证码发送至指定邮箱
        if (!RegexUtil.emailVerify(userEmail) || !userEmail.endsWith("@wolaibao.com") || !userEmail.endsWith("@zhongbao.email") ) {
            throw new WlbException("用户账户错误,请重新输入");
        }
        AdminUser adminUser = findAdminByAccount(userEmail);
        if (null == adminUser || StringUtils.isBlank(adminUser.getUsername())
                || adminUser.getStatus()!=0) {
            throw new WlbException("用户账户错误,请重新输入");
        }
        AdminAuth lastAuth = adminAuthDao.selectLastVcode(userEmail);
        if (lastAuth != null && System.currentTimeMillis() - lastAuth.getUpdateTime().getTime() < (1 * 60 * 1000)) {
            throw new WlbException("验证码已经发送至邮箱请勿重复获取");
        }

        String vcode;
        if (lastAuth == null || System.currentTimeMillis() - lastAuth.getExpireTime() > 0) {
            vcode = generateVcode(userEmail);
            AdminAuth adminAuth = new AdminAuth();
            adminAuth.setEmail(userEmail);
            adminAuth.setVcode(vcode);
            adminAuth.setExpireTime(System.currentTimeMillis() + expireTime);
            adminAuthDao.insert(adminAuth);
        } else {
            vcode = lastAuth.getVcode();
            adminAuthDao.update(lastAuth);
        }
        MsgService.sendMail(userEmail, "管理后台登录验证", "管理后台登录验证码为:" + vcode + "\n有效期为24小时!");
        return "我有效期为24来保管理后台登录验证已经发送至邮箱,小时,请注意保管验证码";
    }

    private AdminUser findAdminByAccount(String userEmail) {
        return adminUserDao.selectByAccount(userEmail);
    }
}

2.3 在 MsgService 发送邮件接口中:

@Service
public class MsgService {
/**
 * 调用邮件发送接口
 * @param to
 * @param subject
 * @param content
 */
 public static void sendMail(String to, String subject, String content) {
    try {
        NetRequest mailRequest = new NetRequest(ClientApiMethod.MSG_EMAIL).setMethod(RequestMethod.GET);
         Map<String, Object> params = new HashMap<>();
         params.put("to", to);
         params.put("content", content);
         params.put("subject", subject);
         mailRequest.setParams(params);
         String msgRsp = new HttpExecutor().execute(mailRequest, String.class);
         Loggers.MANAGE.debug("REQUEST email : ", to, "\nRESPONSE", msgRsp.trim());
     } catch (Exception e) {
        Loggers.MANAGE.error("SendMsg error: \n", e);
     }
    }
}

2.4 在NetRequest中

public class NetRequest {
    /**
     * 请求方法
     */
    private RequestMethod method = RequestMethod.GET;
    /**
     * 请求url
     */
    private String path;

    /**
     * 标示
     */
    private String tag;

    public NetRequest(String url) {
        this.path = url;
        this.tag = "request-" + hashCode();
    }
    public RequestMethod getMethod() {
        return method;
    }

    public NetRequest setMethod(RequestMethod method) {
        this.method = method;
        return this;
    }
    public String getUrl() {
        return path;
    }

    public NetRequest setUrl(String path) {
        this.path = path;
        return this;
    }

    public String getTag() {
        return tag;
    }

    public NetRequest setTag(String tag) {
        this.tag = tag;
        return this;
    }

}

2.5 在ClientApiMethod中

public class ClientApiMethod {
private static final String MSG_HOST = Config.getInstance().getHttpMsgHost();
 public static final String MSG_EMAIL = MSG_HOST + "/msg/email.json";
 public static final String MSG_EMAIL_HTML = MSG_HOST + "/msg/emailHtml.json";
 public static final String APL_NOTIFY = "/taskDistribution/taskDistributionManager.json";
}

2.6 在HttpExecutor中

public class HttpExecutor {
    public List<HttpTask> taskList = new ArrayList<HttpTask>();
    /**
     * 同步执行请求
     * @param netRequest 请求
     * @param cls  接口响应结果Class
     * @param <T>
     * @return
     */
    public <T> T execute(NetRequest netRequest,Class<T> cls) {
        HttpTask httpTask = new HttpTask().setHttpParam(netRequest);
        taskList.add(httpTask);
        String responseData= httpTask.start();
        if(StrUtil.isBlank(responseData))return null;
        T response =null;
        try {
            response = netRequest.getDataParser().parseResponse(responseData, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}

 

 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java实现邮箱验证注册可以分为以下步骤: 1. 在注册页面中,用户输入注册信息,包括邮箱地址和密码等。 2. 点击注册按钮后,服务器端生成一个随机的验证码,并将验证码邮箱地址存储在数据库中。 3. 服务器端将验证码通过邮件发送给用户,用户收到邮件后将验证码输入到注册页面中。 4. 用户点击验证按钮,客户端将用户输入的邮箱地址和验证码发送到服务器端。 5. 服务器端从数据库中查询该邮箱地址对应的验证码是否正确,如果正确则将用户信息存储到数据库中。 以下是Java代码示例: 1. 生成验证码 ``` public static String generateVerificationCode() { int length = 6; String code = ""; for (int i = 0; i < length; i++) { int rand = (int) (Math.random() * 10); code += rand; } return code; } ``` 2. 发送邮件 ``` public static void sendEmail(String recipient, String code) { String subject = "邮箱验证"; String content = "您的验证码为:" + code + ",请在注册页面中输入此验证码以完成邮箱验证。"; String smtpHost = "smtp.xxx.com"; // 邮件服务器地址 String smtpPort = "25"; // 邮件服务器端口 String from = "xxx@xxx.com"; // 发件人邮箱地址 String username = "xxx"; // 发件人用户名 String password = "xxx"; // 发件人密码 Properties props = new Properties(); props.setProperty("mail.smtp.host", smtpHost); props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setContent(content, "text/html;charset=UTF-8"); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } } ``` 3. 验证验证码 ``` public static boolean verifyCode(String email, String code) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; boolean result = false; try { conn = getConnection(); pstmt = conn.prepareStatement("SELECT * FROM verification_code WHERE email = ? AND code = ?"); pstmt.setString(1, email); pstmt.setString(2, code); rs = pstmt.executeQuery(); if (rs.next()) { result = true; } } catch (SQLException e) { e.printStackTrace(); } finally { close(conn, pstmt, rs); } return result; } ``` 4. 存储用户信息 ``` public static void saveUser(User user) { Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); pstmt = conn.prepareStatement("INSERT INTO user(email, password) VALUES (?, ?)"); pstmt.setString(1, user.getEmail()); pstmt.setString(2, user.getPassword()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(conn, pstmt, null); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员学习圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值