Java实现注册邮箱激活账户实例代码
在网站注册时一般都会要验证注册用户身份的合法性,通常的做法是提供手机号验证或者邮箱验证。
手机验证:填写手机号码,点击发送验证码,接收后填写验证码比对,无误后注册成功。
邮箱验证:注册时填写邮箱账号,点击注册,网站邮箱会给该邮箱发送一封激活邮件,用户点击后激活该账号。
这里通过实例来介绍一下邮箱验证的实现过程,例子可以运行,暂时没有发现什么问题,不过也可能有不安全的地方,欢迎大家指正。
实现思路
注册时填写邮箱,点击注册时网站系统邮箱发送激活验证链接到此邮箱,用户来激活账户
点击注册,系统邮箱会发送一封激活邮件到你填写的邮箱账号中
在没有进行激活操作前,设定某个字段状态是0,表示此账号未激活,不可以使用或者某些功能受限
激活操作之后,将activated字段更新为1,这样就完成了激活操作
那么这里还有一个codeurl字段,他的作用是存入一个唯一标识的随机码,这个随机码由用户名和uuid唯一标识的随机数组成,这样做的目的是防止用户使用不存在的邮箱又修改链接中的参数来激活账户,将链接中的随机码和数据库中的比对,来达到相对安全的激活。
下面是具体的代码
首先是注册的servlet,这里主要测试激活账号的功能,注册代码有点low,不安全,将就看一下
package org.amuxia.emailtest.servlet; import java.io.ioexception; import java.sql.resultset; import java.sql.sqlexception; import java.util.uuid; 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 org.amuxia.emailtest.pojo.user; import org.amuxia.emailtest.utils.emailutils; import org.amuxia.emailtest.utils.myjdbc; /** * @author amuxia * 2017年7月24日 */ @webservlet("/registservlet") public class registservlet extends httpservlet { private static final long serialversionuid = 1l; protected void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string username = request.getparameter("username"); string password = request.getparameter("password"); string email = request.getparameter("email"); string codeurl = uuid.randomuuid().tostring(); user user = new user(); user.setusername(username); user.setpassword(password); user.setemail(email); user.setactivated(false); //刚注册默认是没有激活状态 string sql = "insert into tb_user(username,password,email,activated,codeurl) value (?,?,?,?,?) "; myjdbc.insert(sql, false, username,password,email,0,codeurl);//注册信息插入数据库 string querysql = "select * from tb_user where email=?"; resultset rs = myjdbc.query(querysql, email); try { if(rs.next()){ user.setid(rs.getint(1)); } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } // 注册成功后,发送帐户激活链接 request.getsession().setattribute("user", user); emailutils.sendaccountactivateemail(user); request.getrequestdispatcher("/web-inf/jsp/success.jsp").forward(request,response); } }
激活账号的servlet,也就是更新操作
package org.amuxia.emailtest.servlet; import java.io.ioexception; import java.sql.resultset; import java.sql.sqlexception; 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 org.amuxia.emailtest.pojo.user; import org.amuxia.emailtest.utils.generatelinkutils; import org.amuxia.emailtest.utils.myjdbc; /** * @author amuxia * 2017年7月24日 */ @webservlet("/activateservlet") public class activateservlet extends httpservlet{ private static final long serialversionuid = 1l; @override protected void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub string idvalue = request.getparameter("id"); system.out.println(idvalue); int id = -1; try { id = integer.parseint(idvalue); } catch (numberformatexception e) { e.printstacktrace(); } string sql = "select * from tb_user where id=?"; resultset rs= myjdbc.query(sql, id); user user = new user(); try { if(rs.next()){ user.setid(rs.getint(1)); user.setusername(rs.getstring(2)); user.setpassword(rs.getstring(3)); user.setemail(rs.getstring(4)); user.setactivated(rs.getboolean(5)); user.setcodeurl(rs.getstring(6)); } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } //验证无误,状态更改为1,即激活 if(generatelinkutils.verifycheckcode(user, request)){ string updsql = "update tb_user set activated =1 where id=?"; myjdbc.execute(updsql, id); user.setactivated(true); request.getsession().setattribute("user", user); request.getrequestdispatcher("/web-inf/jsp/pass.jsp").forward(request, response); } } }
发送email的工具类
package org.amuxia.emailtest.utils; import java.util.date; import java.util.properties; import javax.mail.authenticator; import javax.mail.message.recipienttype; import javax.mail.passwordauthentication; import javax.mail.session; import javax.mail.transport; import javax.mail.internet.internetaddress; import javax.mail.internet.mimemessage; import org.amuxia.emailtest.pojo.user; /** * @author amuxia * 2017年7月24日 */ public class emailutils { private static final string from = "要发送邮件的邮箱,这个例子是163邮箱"; public static void sendaccountactivateemail(user user) { session session = getsession(); mimemessage message = new mimemessage(session); try { message.setsubject("这是一封激活账号的邮件,复制链接到地址栏来激活他"); message.setsentdate(new date()); message.setfrom(new internetaddress(from)); message.setrecipient(recipienttype.to, new internetaddress(user.getemail())); message.setcontent("<a target='_blank' href=''>"+generatelinkutils.generateactivatelink(user)+"</a>","text/html;charset=utf-8"); transport.send(message); } catch (exception 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"); props.setproperty("mail.smtp.port", "25"); props.setproperty("mail.smtp.auth", "true"); session session = session.getinstance(props, new authenticator() { @override protected passwordauthentication getpasswordauthentication() { return new passwordauthentication(from, "上面邮箱的密码"); } }); return session; } }
这里需要注意一下,以上例子配置的是163邮箱,需要进行邮箱客户端的授权,授权之后,网易邮箱会发来一份客户端授权码作为替代邮箱密码,代码里填写的密码其实是授权码,配置好邮箱最好发一份邮件测试一下,有时程序出问题很可能是邮箱客户端根本发不了邮件
加密账户激活链接生成的工具类
package org.amuxia.emailtest.utils; import java.security.messagedigest; import java.security.nosuchalgorithmexception; import javax.servlet.servletrequest; import org.amuxia.emailtest.pojo.user; /** * @author amuxia * 2017年7月24日 */ public class generatelinkutils { private static final string check_code = "checkcode"; public static string generateactivatelink(user user) { return "http://localhost/emaildemo/activateservlet?id=" + user.getid() + "&" + check_code + "=" + generatecheckcode(user); } /** * 生成校验码,用户名+uuid唯一标识符,为安全把他们加密发送 * @param user * @return */ public static string generatecheckcode(user user) { string username = user.getusername(); string randomcode = user.getcodeurl(); return md5(username + ":" + randomcode); } /** * 接收回来的校验码和发送出去的是不是同一份 * @param user * @param request * @return */ public static boolean verifycheckcode(user user,servletrequest request) { string checkcode = request.getparameter(check_code); system.out.println(generatecheckcode(user).equals(checkcode)); return true; } private static string md5(string string) { messagedigest md = null; try { md = messagedigest.getinstance("md5"); md.update(string.getbytes()); byte[] md5bytes = md.digest(); return bytes2hex(md5bytes); } catch (nosuchalgorithmexception e) { e.printstacktrace(); system.out.println("md5这里出错了"); } return null; } private static string bytes2hex(byte[] bytearray) { stringbuffer strbuf = new stringbuffer(); for (int i = 0; i < bytearray.length; i++) { if(bytearray[i] >= 0 && bytearray[i] < 16) { strbuf.append("0"); } strbuf.append(integer.tohexstring(bytearray[i] & 0xff)); } return strbuf.tostring(); } }
还有一个操作数据库的封装类,myjdbc,前面博客有写,代码挺长,就不贴了,这是链接:
实体类user
package org.amuxia.emailtest.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; } public user() { super(); } }
注册的jsp
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <title>注册</title> </head> <body> <form action="/emaildemo/registservlet" method="post"> 用户名:<input type="text" name="username"><br/> 密码:<input type="password" name="password"><br/> 邮箱:<input type="text" name="email"><br/> <input type="submit" value="注册"> </form> </body> </html>
用到的包?
邮箱验证的大概功能就完成了,但是还有很多不足之处,貌似应该设置一个过期时间。等等。。。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。