javaweb实现邮箱验证码

参考的博客(大佬们)

六位随机验证码链接: 点击这里.
cookie技术链接: 点击这里.
关键邮箱技术链接: 点击这里.

邮箱验证的知识点

首先是前端代码,使用cookie技术存储验证码,超时删除,生成随机验证码
然后就是ajax技术和jQuery的一些使用
引入包pom.xml配置
mail工具类线程(我还没学)
后台代码实现

cookie和验证码

//设计Cookie的值
	function setCookie(name,value){ 
	    var Days = 30; 
	    var exp = new Date(); 
	    exp.setTime(exp.getTime() + Days*24*60*60*1000); 
	    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
	}
	
	//获取Cookie的值
	function getCookie(name){ 
	    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	 
	    if(arr=document.cookie.match(reg))
	        return unescape(arr[2]); 
	    else 
	        return null; 
	}
	
	//删除Cookie中的值
	function delCookie(name){ 
	    var exp = new Date(); 
	    exp.setTime(exp.getTime() - 1); 
	    var cval=getCookie(name); 
	    if(cval!=null) 
	        document.cookie= name + "="+cval+";expires="+exp.toGMTString(); 
	}

前端ajax和一些代码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script src="https://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
	<script src="https://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
	<script src="https://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
		<meta charset="utf-8">
		<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<div class="widget-content" id="demo1">
<span style="white-space:pre">	</span><input type="text" name="text" id="text11">
<input type="button" name="test" value="获取验证码" id="test11">
<input type="button" name="yanz" value="验证"id="yanz11">
</div>
<script type="text/javascript">
    $("[name=yanz]").click(function(){
    	var a=$("[name=text]").val();
    	var code17=getCookie("code");
    	if(a==code17)
    		alert("成功");
    	else
    		alert("失败");
    });
	function times(){
		var time = getCookie("time");
		if(time == null){
			time = 10;
		}
		time--;
		setCookie("time", time);
		//设置页面样式
		//$("[name=test]").html(time+"秒后重新获取");
		//过1秒递归调用times()函数
		document.getElementById("test11").value=time+"秒后重新获取";
		var funcs = setTimeout("times()", 1000);
		document.getElementById("test11").disabled = true;
		if ( time <= 0 ){
			//删除Cookie中的值
			delCookie("time");
			delCookie("code");
			//删除递归调用函数
			clearTimeout(funcs);
			document.getElementById("test11").value="重新发送";
			document.getElementById("test11").disabled = false;
		}
	}
	$("[name=test]").click(function(){
		    var code = "123456";
			setCookie("code", code);
			var a=getCookie("code");
			alert(a); 
			times();
		});
			</script>
</body>

Ajax的使用

$("[name=zhuce]").click(function(){
    		var userid =$("[name=userid]").val();
    		var password =$("[name=password]").val();
    		var username =$("[name=username]").val();
    		var mailbox =$("[name=password]").val();
    		var a=$("[name=yanzcode]").val();
    		var code17=getCookie("code");
        	if(a!=code17)
        		alert("验证码错误");
    		var paramas={"userid":userid,"username":username,"password":password,"mailbox":mailbox};
    		$.ajax({
    			type:"post",
    			url:"${ctx}/user/register.do",
    			data:paramas,
    			datatype:"json",
    			success:function(data){
    				if(data==1){
    					alert("注册成功");
    					window.location.href = 'index.jsp';
    				}
    				else
    					alert("注册失败");
    			},
    		error:function(){
    			alert("失败");
    		}
    		})
    	});

发送验证码的前端js

$("[name=mailsend]").click(function(){
    		var mail =$("[name=mailbox]").val();
    		if(mail==""){
    			alert("请填写邮箱信息");
    			return;
    		}
    		var code = Math.random().toString().slice(-6);
    		setCookie("code",code);
    		times();
    		var paramas1={"mailbox":mail,"code":code};
    		$.ajax({
    			type:"post",
    			url:"${ctx}/user/mailsend.do",
    			data:paramas1,
    			datatype:"json",
    			success:function(data){
    				if(data==1){
    					alert("发送成功");
    				}
    				else
    					alert("发送失败");
    			},
    			error:function(){
        			alert("失败");
        		}
    		})
    	})//

pom.xml的配置

<!-- c3p0依赖 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!-- JavaMail相关依赖 -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>

Mail工具类

package com.sixman.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import com.sixman.domain.UserPo;
import com.sixman.repository.UserRepository;
import com.sun.mail.util.MailSSLSocketFactory;


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><br/><h3>"+code+"</h3></body></html>";
            message.setContent(content, "text/html;charset=UTF-8");
            // 3.发送邮件
            Transport.send(message);
            System.out.println("邮件成功发送!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

后台具体代码

@Controller
@RequestMapping("/user/")
//类里面的方法
@RequestMapping("mailsend")
	public void mailsend(HttpServletRequest request,HttpServletResponse response) throws IOException{
	    // 这里可以验证各字段是否为空
	    String email=request.getParameter("mailbox");
	    //生成激活码
	    String code=request.getParameter("code");
	    new Thread(new MailUtil(email, code)).start();
	    PrintWriter a1=response.getWriter();
	    a1.print("1");
	}

先就这样吧,记录下来了

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值