注册邮箱激活功能


转自:http://www.2cto.com/kf/201312/268157.html

最近从项目分离出来的注册邮箱激活功能,整理一下,方便下次使用

RegisterValidateService.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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(email);
         sb.append( "&validateCode=" );
         sb.append(user.getValidateCode());
         sb.append( "" );
         
         //发送邮件
         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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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;
     }
 
}
</string,></string,>

UserModel.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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();
         }
     }
 
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值