思路:

1.注册帐户时把用户存入数据库并且设置用户状态不可用,同时给注册的邮箱发邮件。

2.邮箱的内容应该是链接到项目的激活方法,并且传入参数(注册的邮箱和验证码)。(http://localhost:8080/email/user/register?action=activate&email=1434244213@qq.com&validateCode=b4dc9b79b75d9aa7d6c332e780a375c2)

3.点击链接会对邮箱、验证码、激活时间进行验证,如果激活成功,更改用户状态为可用。

 

service层代码

import java.text.ParseException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.dao.UserDao;
import com.app.tools.MD5Util;
import com.app.tools.SendEmail;
import com.app.tools.SendMail;
import com.app.tools.ServiceException;
import com.code.model.UserModel;

/**
 * 
 * @author BuNuo
 */
@Service
public class RegisterValidateService {

    @Autowired
    private UserDao userDao;
    
    @Autowired
    private  HttpServletRequest request;

    /**
     * 处理注册
     */

    public void processregister(String email){
        UserModel user=new UserModel();
        Long as=5480l;
        user.setId(as);
        user.setName("BuNuo");
        user.setPassword("111111");
        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>");
        String url = request.getScheme() //当前链接使用的协议
                +"://" + request.getServerName()//服务器地址 
                + ":" + request.getServerPort() //端口号 
                + request.getContextPath(); //应用名称,如果应用名称为
        sb.append("<a href="+url+"/user/register?action=activate&email=");
        sb.append(email); 
        sb.append("&validateCode="); 
        sb.append(user.getValidateCode());
        sb.append("\">http://localhost:8088/email/user/register?action=activate&email="); 
        sb.append(email);
        sb.append("&validateCode=");
        sb.append(user.getValidateCode());
        sb.append("</a>");

        //发送邮件
        //new SendMail().sendMail(email, sb.toString());
        new 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 {  
                       System.out.println("激活码不正确");  
                    }  
                } else { System.out.println("激活码已过期!");  
                }  
            } else {
               System.out.println("邮箱已激活,请登录!");  
            }  
        } else {
            System.out.println("该邮箱未注册(邮箱地址不存在)!");  
        }  

    }
}

 

MD5Util.java

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

}

 

SendEmail.java    发送邮件的方法,调用此方法传入邮箱和发送内容即可(new SendEmail().send(email, content);)

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 BuNuo
 */
public class SendEmail {

    public static final String HOST = "smtp.163.com";
    public static final String PROTOCOL = "smtp";   
    public static final int PORT = 8080;
    public static final String FROM = "";//发件人的email
    public static final String PWD = "";//发件人密码

    /**
     * 获取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 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();
        }
    }
}

 demo地址:http://download.csdn.net/detail/qq_33347991/9711788

 posted on 2016-11-23 19:52  布诺  阅读(2387)  评论(0编辑  收藏  举报