Java注册邮箱激活验证实现代码
最近从项目分离出来的注册邮箱激活功能,整理一下,方便下次使用
registervalidateservice.java
package com.app.service.impl;
import java.text.parseexception;
import java.util.date;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import com.app.dao.userdao;
import com.app.tools.md5tool;
import com.app.tools.md5util;
import com.app.tools.sendemail;
import com.app.tools.serviceexception;
import com.code.model.usermodel;
/**
*
* @author qixuan.chen
*/
@service
public class registervalidateservice {
@autowired
private userdao userdao;
/**
* 处理注册
*/
public void processregister(string email){
usermodel user=new usermodel();
long as=5480l;
user.setid(as);
user.setname("xiaoming");
user.setpassword("324545");
user.setemail(email);
user.setregistertime(new date());
user.setstatus(0);
///如果处于安全,可以将激活码处理的更复杂点,这里我稍做简单处理
//user.setvalidatecode(md5tool.md5encrypt(email));
user.setvalidatecode(md5util.encode2hex(email));
userdao.save(user);//保存注册信息
///邮件的内容
stringbuffer sb=new stringbuffer("点击下面链接激活账号,48小时生效,否则重新注册账号,链接只能使用一次,请尽快激活!</br>");
sb.append("<a href=\"http://localhost:8080/springmvc/user/register?action=activate&email=");
sb.append(email);
sb.append("&validatecode=");
sb.append(user.getvalidatecode());
sb.append("\">http://localhost:8080/springmvc/user/register?action=activate&email=");
sb.append(email);
sb.append("&validatecode=");
sb.append(user.getvalidatecode());
sb.append("</a>");
//发送邮件
sendemail.send(email, sb.tostring());
system.out.println("发送邮件");
}
/**
* 处理激活
* @throws parseexception
*/
///传递激活码和email过来
public void processactivate(string email , string validatecode)throws serviceexception, parseexception{
//数据访问层,通过email获取用户信息
usermodel user=userdao.find(email);
//验证用户是否存在
if(user!=null) {
//验证用户激活状态
if(user.getstatus()==0) {
///没激活
date currenttime = new date();//获取当前时间
//验证链接是否过期
currenttime.before(user.getregistertime());
if(currenttime.before(user.getlastactivatetime())) {
//验证激活码是否正确
if(validatecode.equals(user.getvalidatecode())) {
//激活成功, //并更新用户的激活状态,为已激活
system.out.println("==sq==="+user.getstatus());
user.setstatus(1);//把状态改为激活
system.out.println("==sh==="+user.getstatus());
userdao.update(user);
} else {
throw new serviceexception("激活码不正确");
}
} else { throw new serviceexception("激活码已过期!");
}
} else {
throw new serviceexception("邮箱已激活,请登录!");
}
} else {
throw new serviceexception("该邮箱未注册(邮箱地址不存在)!");
}
}
}
registercontroller.java
package com.app.web.controller;
import java.text.parseexception;
import javax.annotation.resource;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.servlet.modelandview;
import com.app.service.impl.registervalidateservice;
import com.app.tools.serviceexception;
@controller
public class registercontroller {
@resource
private registervalidateservice service;
@requestmapping(value="/user/register",method={requestmethod.get,requestmethod.post})
public modelandview load(httpservletrequest request,httpservletresponse response) throws parseexception{
string action = request.getparameter("action");
system.out.println("-----r----"+action);
modelandview mav=new modelandview();
if("register".equals(action)) {
//注册
string email = request.getparameter("email");
service.processregister(email);//发邮箱激活
mav.addobject("text","注册成功");
mav.setviewname("register/register_success");
}
else if("activate".equals(action)) {
//激活
string email = request.getparameter("email");//获取email
string validatecode = request.getparameter("validatecode");//激活码
try {
service.processactivate(email , validatecode);//调用激活方法
mav.setviewname("register/activate_success");
} catch (serviceexception e) {
request.setattribute("message" , e.getmessage());
mav.setviewname("register/activate_failure");
}
}
return mav;
}
}
userdao.java(这里个人没有做入库操作,只是利用集合,做过效果出来0_0)
package com.app.dao;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.date;
import java.util.hashmap;
import org.springframework.stereotype.repository;
import com.code.model.usermodel;
/**
*
* @author qixuan.chen
*/
@repository
public class userdao {
public hashmap<string, string> map=new hashmap<string, string>();
/**
* @保存注册信息
* private long id;
private string name;
private string password;
private string email;//注册账号
private int status;//激活状态
private string validatecode;//激活码
private date registertime;//注册时间
*/
public void save(usermodel user){
system.out.println("cicicici");
map.put("id", string.valueof(user.getid()));
map.put("email", user.getemail());
map.put("validatecode", user.getvalidatecode());
simpledateformat sdf=new simpledateformat("yyyymmddhhmmss");
string time=sdf.format(user.getregistertime());
map.put("registertime", time);
int status=user.getstatus();
map.put("status", string.valueof(status));
map.put("name", user.getname());
string t2=sdf.format(user.getlastactivatetime());
map.put("activelasttime", string.valueof(t2));
system.out.println("=======s========="+status);
}
/**
* @更新 user
*/
public void update(usermodel user){
map.put("email", user.getemail());
map.put("validatecode", user.getvalidatecode());
date time=user.getregistertime();
map.put("registertime", string.valueof(time));
int status=user.getstatus();
map.put("status", string.valueof(status));
system.out.println("=======st========="+status);
}
/**
* @throws parseexception
* @查找信息
*/
public usermodel find(string email) throws parseexception{
usermodel user=new usermodel();
user.setemail(map.get("email"));
user.setname(map.get("name"));
simpledateformat sdf=new simpledateformat("yyyymmddhhmmss");
date day=sdf.parse(map.get("registertime"));
user.setregistertime(day);
user.setstatus(integer.valueof(map.get("status")));
user.setvalidatecode(map.get("validatecode"));
return user;
}
}
usermodel.java
package com.code.model;
import java.beans.transient;
import java.util.calendar;
import java.util.date;
public class usermodel {
private long id;
private string name;
private string password;
private string email;//注册账号
private int status=0;//激活状态
private string validatecode;//激活码
private date registertime;//注册时间
/////////////////
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
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 int getstatus() {
return status;
}
public void setstatus(int status) {
this.status = status;
}
public string getvalidatecode() {
return validatecode;
}
public void setvalidatecode(string validatecode) {
this.validatecode = validatecode;
}
public date getregistertime() {
return registertime;
}
public void setregistertime(date registertime) {
this.registertime = registertime;
}
/////////////////////////
@transient
public date getlastactivatetime() {
calendar cl = calendar.getinstance();
cl.settime(registertime);
cl.add(calendar.date , 2);
return cl.gettime();
}
}
sendemail.java
package com.app.tools;
import java.util.date;
import java.util.properties;
import javax.mail.authenticator;
import javax.mail.message;
import javax.mail.messagingexception;
import javax.mail.passwordauthentication;
import javax.mail.session;
import javax.mail.transport;
import javax.mail.internet.internetaddress;
import javax.mail.internet.mimemessage;
/**
*
* @author qixuan.chen
*/
public class sendemail {
public static final string host = "smtp.163.com";
public static final string protocol = "smtp";
public static final int port = 25;
public static final string from = "xxxxx@xx.com";//发件人的email
public static final string pwd = "123456";//发件人密码
/**
* 获取session
* @return
*/
private static session getsession() {
properties props = new properties();
props.put("mail.smtp.host", host);//设置服务器地址
props.put("mail.store.protocol" , protocol);//设置协议
props.put("mail.smtp.port", port);//设置端口
props.put("mail.smtp.auth" , true);
authenticator authenticator = new authenticator() {
@override
protected passwordauthentication getpasswordauthentication() {
return new passwordauthentication(from, pwd);
}
};
session session = session.getdefaultinstance(props , authenticator);
return session;
}
public static void send(string toemail , string content) {
session session = getsession();
try {
system.out.println("--send--"+content);
// instantiate a message
message msg = new mimemessage(session);
//set message attributes
msg.setfrom(new internetaddress(from));
internetaddress[] address = {new internetaddress(toemail)};
msg.setrecipients(message.recipienttype.to, address);
msg.setsubject("账号激活邮件");
msg.setsentdate(new date());
msg.setcontent(content , "text/html;charset=utf-8");
//send the message
transport.send(msg);
}
catch (messagingexception mex) {
mex.printstacktrace();
}
}
}
md5util.java
package com.app.tools;
import java.io.unsupportedencodingexception;
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
public class md5util {
/**
* 将源字符串使用md5加密为字节数组
* @param source
* @return
*/
public static byte[] encode2bytes(string source) {
byte[] result = null;
try {
messagedigest md = messagedigest.getinstance("md5");
md.reset();
md.update(source.getbytes("utf-8"));
result = md.digest();
} catch (nosuchalgorithmexception e) {
e.printstacktrace();
} catch (unsupportedencodingexception e) {
e.printstacktrace();
}
return result;
}
/**
* 将源字符串使用md5加密为32位16进制数
* @param source
* @return
*/
public static string encode2hex(string source) {
byte[] data = encode2bytes(source);
stringbuffer hexstring = new stringbuffer();
for (int i = 0; i < data.length; i++) {
string hex = integer.tohexstring(0xff & data[i]);
if (hex.length() == 1) {
hexstring.append('0');
}
hexstring.append(hex);
}
return hexstring.tostring();
}
/**
* 验证字符串是否匹配
* @param unknown 待验证的字符串
* @param okhex 使用md5加密过的16进制字符串
* @return 匹配返回true,不匹配返回false
*/
public static boolean validate(string unknown , string okhex) {
return okhex.equals(encode2hex(unknown));
}
}
serviceexception.java
package com.app.tools;
public class serviceexception extends exception {
private static final long serialversionuid = -1708015121235851228l;
public serviceexception(string message) {
super(message);
}
}
jsp页面
registeremailvalidae.jsp
<h2>注册激活</h2>
<form action="user/register?action=register" method="post">
email:<input type="text" id="email" name="email" value="" >
<input type="submit" value="提交">
</form>
register_success.jsp
<body>
恭喜你注册成功!请到注册的邮箱点击链接激活!
</body>
activate_success.jsp:
<body>
账号激活成功,点击这里去登录!
</body>
activate_failure.jsp:
<body>
激活失败!错误信息:${message }
</body>
效果图:
1
2
3
4
5
上一篇: C# BackgroundWorker组件学习入门介绍
下一篇: 用CSS实现文字变图象特效