Spring技术_邮箱注册_激活_获取验证码

项目结构

项目中用到的sql:

 1 create database hrSystem;
 2  use hrSystem;
 3  
 4  CREATE TABLE `emailverificationcode` (
 5    `id` int(11) NOT NULL AUTO_INCREMENT,
 6    `email` varchar(50) DEFAULT NULL,
 7    `password` varchar(50) DEFAULT NULL,
 8    `activie` int(11) DEFAULT '0',
 9    PRIMARY KEY (`id`)
10  ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=gb2312;

登录界面:

注册信息:

注册成功:

邮箱激活:

成功激活:

进行登录:

获取验证码:

输入验证码:

登录成功:

当然,在你输入验证码错误的时候,系统会让你重新登录。

==============================================

/EmailforVerificationCode/src/com/b510/action/ActiveEmailAction.java

 1 package com.b510.action;
 2  
 3  import com.b510.domain.Emailverificationcode;
 4  import com.b510.service.EmailVerificationCodeService;
 5  import com.opensymphony.xwork2.ActionSupport;
 6  
 7  /**
 8   * 激活邮箱
 9   * 
10   * @author Hongten
11   * 
12   */
13  public class ActiveEmailAction extends ActionSupport {
14  
15      /**
16       * identification number
17  */
18      private static final long serialVersionUID = -4621519681196499222L;
19      /**
20       * id号
21  */
22      private int id;
23      /**
24       * 登录的时候填写的email
25  */
26      private String email;
27      /**
28       * 登录的时候填写的password
29  */
30      private String password;
31  
32      public int getId() {
33          return id;
34      }
35  
36      public void setId(int id) {
37          this.id = id;
38      }
39  
40      public String getEmail() {
41          return email;
42      }
43  
44      public void setEmail(String email) {
45          this.email = email;
46      }
47  
48      public String getPassword() {
49          return password;
50      }
51  
52      public void setPassword(String password) {
53          this.password = password;
54      }
55  
56      public int getActive() {
57          return active;
58      }
59  
60      public void setActive(int active) {
61          this.active = active;
62      }
63  
64      public EmailVerificationCodeService getEmailVerificationCodeService() {
65          return emailVerificationCodeService;
66      }
67  
68      public void setEmailVerificationCodeService(
69              EmailVerificationCodeService emailVerificationCodeService) {
70          this.emailVerificationCodeService = emailVerificationCodeService;
71      }
72  
73      /**
74       * 是否激活
75  */
76      private int active;
77      /**
78       * 通过spring的IoC方式注入EmailVerificationCodeService一个实例
79  */
80      private EmailVerificationCodeService emailVerificationCodeService;
81  
82      // 激活邮箱
83      private String activeEmail() {
84          Emailverificationcode emailverificationcode = new Emailverificationcode();
85          emailverificationcode.setId(getId());
86          emailverificationcode.setEmail(getEmail());
87          emailverificationcode.setPassword(getPassword());
88          emailverificationcode.setActive(getActive());
89          getEmailVerificationCodeService().updateActive(emailverificationcode);
90          return "active";
91      }
92  
93      @Override
94      public String execute() throws Exception {
95          return activeEmail();
96      }
97  
98  }
View Code

/EmailforVerificationCode/src/com/b510/action/EmailVerificationCodeAction.java

package com.b510.action;
 
 import com.b510.domain.Emailverificationcode;
 import com.b510.service.EmailVerificationCodeService;
 import com.opensymphony.xwork2.ActionContext;
 import com.opensymphony.xwork2.ActionSupport;
 
 /**
  * 
  * @author Hongten
  * 
  */
 public class EmailVerificationCodeAction extends ActionSupport {
 
     /**
      * identification number
 */
     private static final long serialVersionUID = 1514692413102258755L;
 
     /**
      * 登录的时候填写的email
 */
     private String email;
     /**
      * 登录的时候填写的password
 */
     private String password;
     /**
      * id号
 */
     private int id;
     /**
      * 是否激活
 */
     private int active;
 
     public int getId() {
         return id;
     }
 
     public void setId(int id) {
         this.id = id;
     }
 
     public int getActive() {
         return active;
     }
 
     public void setActive(int active) {
         this.active = active;
     }
 
     /**
      * 登录的时候填写的验证码
 */
     private String verificationCode;
     /**
      * 通过spring的IoC方式注入EmailVerificationCodeService一个实例
 */
     private EmailVerificationCodeService emailVerificationCodeService;
 
     @Override
     public String execute() throws Exception {
         // 如果email,password都不为null的时候,执行登录操作
         if (getEmail() != null && getPassword() != null) {
             Emailverificationcode emailVerificationCode = new Emailverificationcode();
             emailVerificationCode = getEmailVerificationCodeService()
                     .getByEmailAndPassword(getEmail(), getPassword());
             if (emailVerificationCode.getActive() == 0) {
                 return "error";
             } else {
                 String verificationCode = getEmailVerificationCodeService()
                         .getRandomChar()
                         + getEmailVerificationCodeService().getRandomChar()
                         + getEmailVerificationCodeService().getRandomChar()
                         + getEmailVerificationCodeService().getRandomChar();
                 String content = "验证码是:" + verificationCode;
                 // 创建ActionContext实例
                 ActionContext ctx = ActionContext.getContext();
                 // 获取HttpSession中的verificationCode属性
                 ctx.getSession().put("verificationCode", verificationCode);
                 getEmailVerificationCodeService()
                         .sendEmail(
                                 getEmail(),
                                 EmailVerificationCodeService.SUBJECT_MAIL_GETVERIFICATIONCODE,
                                 content);
                 return "input";
             }
         }
         return "error";
     }
 
     public String getEmail() {
         return email;
     }
 
     public EmailVerificationCodeService getEmailVerificationCodeService() {
         return emailVerificationCodeService;
     }
 
     public String getPassword() {
         return password;
     }
 
     public String getVerificationCode() {
         return verificationCode;
     }
 
     // 处理验证码
     public String inputVerificationCode() throws Exception {
         // 创建ActionContext实例
         ActionContext ctx = ActionContext.getContext();
         // 获取HttpSession中的verificationCode属性
         String ver = (String) ctx.getSession().get("verificationCode");
 
         // 如果verificationCode不为null的时候,执行登录操作
         if (getVerificationCode() != null
                 && getVerificationCode().equalsIgnoreCase(ver)) {
             return SUCCESS;
         } else {
             return "errorVerCode";
         }
     }
 
     public void setEmail(String email) {
         this.email = email;
     }
 
     public void setEmailVerificationCodeService(
             EmailVerificationCodeService emailVerificationCodeService) {
         this.emailVerificationCodeService = emailVerificationCodeService;
     }
 
     public void setPassword(String password) {
         this.password = password;
     }
 
     public void setVerificationCode(String verificationCode) {
         this.verificationCode = verificationCode;
     }
 
     public String login() throws Exception {
         return "login";
     }
 
 }
View Code

/EmailforVerificationCode/src/com/b510/action/RegisterAction.java

 1 package com.b510.action;
 2  
 3  import com.b510.domain.Emailverificationcode;
 4  import com.b510.service.EmailVerificationCodeService;
 5  import com.opensymphony.xwork2.ActionSupport;
 6  
 7  /**
 8   * 注册Action
 9   * 
10   * @author Hongten
11   * 
12   */
13  public class RegisterAction extends ActionSupport {
14  
15      /**
16       * identification number
17  */
18      private static final long serialVersionUID = 1L;
19      /**
20       * 注册的email
21  */
22      private String email;
23      /**
24       * 注册的password
25  */
26      private String password;
27  
28      private String url;
29  
30      public String getUrl() {
31          return url;
32      }
33  
34      public void setUrl(String url) {
35          this.url = url;
36      }
37  
38      private EmailVerificationCodeService emailVerificationCodeService;
39  
40      public EmailVerificationCodeService getEmailVerificationCodeService() {
41          return emailVerificationCodeService;
42      }
43  
44      public void setEmailVerificationCodeService(
45              EmailVerificationCodeService emailVerificationCodeService) {
46          this.emailVerificationCodeService = emailVerificationCodeService;
47      }
48  
49      public String getEmail() {
50          return email;
51      }
52  
53      public void setEmail(String email) {
54          this.email = email;
55      }
56  
57      public String getPassword() {
58          return password;
59      }
60  
61      public void setPassword(String password) {
62          this.password = password;
63      }
64  
65      @Override
66      public String execute() throws Exception {
67          // 如果email,password都不为null的时候,执行注册操作
68          if (getEmail() != null && getPassword() != null) {
69              Emailverificationcode emailVerificationCode = new Emailverificationcode();
70              emailVerificationCode.setEmail(getEmail());
71              emailVerificationCode.setPassword(getPassword());
72              emailVerificationCode.setActive(0);
73              getEmailVerificationCodeService().save(emailVerificationCode);
74              Emailverificationcode evc = new Emailverificationcode();
75              evc = getEmailVerificationCodeService().getByEmailAndPassword(
76                      getEmail(), getPassword());
77              String content = "hello,请点击此处进行邮箱激活," + getUrl() + "?id="
78                      + evc.getId() + "&email=" + getEmail() + "&password="
79                      + getPassword() + "&active=1";
80              // 发送邮件进行邮箱激活
81              getEmailVerificationCodeService().sendEmail(getEmail(),
82                      EmailVerificationCodeService.SUBJECT_MAIL_ACTIVE, content);
83              return "login";
84          } else {
85              return "register";
86          }
87      }
88  
89  }
View Code

/EmailforVerificationCode/src/com/b510/dao/EmailVerificationCodeDAO.java

 1 package com.b510.dao;
 2  
 3  import com.b510.domain.Emailverificationcode;
 4  
 5  /**
 6   * EmailVerificationCodeDAO接口
 7   * 
 8   * @author Hongten
 9   * 
10   */
11  public interface EmailVerificationCodeDAO {
12  
13      /**
14       * 保存一条记录
15       * 
16       * @param emailVerificationCode
17       *            需要被持久化的emailVerificationConde实例
18  */
19      public void save(Emailverificationcode emailVerificationCode);
20  
21      /**
22       * 根据id值获取一条记录
23       * 
24       * @param id
25       *            需要获取记录的id值
26       * @return 对应id值的一条记录
27  */
28      public Emailverificationcode getById(int id);
29  
30      /**
31       * 根据email,password获取一条记录
32       * 
33       * @param email
34       *            电子邮箱
35       * @param password
36       *            密码
37       * @return 根据email,password返回相应值的一条记录
38  */
39      public Emailverificationcode getByEmailAndPassword(String email,
40              String password);
41  
42      /**
43       * 根据email,password,active获取一条记录
44       * 
45       * @param email
46       *            电子邮箱
47       * @param password
48       *            密码
49       * @param active
50       * @return 根据email,password,active返回相应值的一条记录
51  */
52      public Emailverificationcode getByEmailAndPassword(String email,
53              String password, int active);
54  
55      /**
56       * 根据id激活对应的email,active默认为0,激活状态为1
57       * 
58       * @param emailverificationcode
59       *            emailverificationcode的一个实例
60       * @return 返回时候激活成功
61  */
62      public int updateActive(Emailverificationcode emailverificationcode);
63  }
View Code

/EmailforVerificationCode/src/com/b510/dao/impl/EmailVerificationCodeDAOImpl.java

package com.b510.dao.impl;
 
 import java.util.List;
 
 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 
 import com.b510.dao.EmailVerificationCodeDAO;
 import com.b510.domain.Emailverificationcode;
 
 public class EmailVerificationCodeDAOImpl extends HibernateDaoSupport implements
         EmailVerificationCodeDAO {
 
     @SuppressWarnings("unchecked")
     public Emailverificationcode getByEmailAndPassword(String email,
             String password) {
         List<Emailverificationcode> evc = (List<Emailverificationcode>) getHibernateTemplate()
                 .find(
                         "from Emailverificationcode where email=? and password=?",
                         email, password);
         if (evc != null && evc.size() >= 1) {
             return evc.get(evc.size() - 1);
         }
         return null;
     }
 
     public Emailverificationcode getById(int id) {
         return getHibernateTemplate().get(Emailverificationcode.class, id);
     }
 
     public void save(Emailverificationcode emailVerificationCode) {
         getHibernateTemplate().save(emailVerificationCode);
     }
 
     public int updateActive(Emailverificationcode emailverificationcode) {
         getHibernateTemplate().update(emailverificationcode);
         return 1;
     }
 
     public Emailverificationcode getByEmailAndPassword(String email,
             String password, int active) {
         return (Emailverificationcode) getHibernateTemplate()
                 .find(
                         "from Emailverificationcode as e where e.email=? and e.password=? and e.active=?",
                         new Object[] { email, password, active });
     }
 
 }
View Code

/EmailforVerificationCode/src/com/b510/domain/Emailverificationcode.java

 1 package com.b510.domain;
 2  
 3  import java.io.Serializable;
 4  
 5  /**
 6   * 电子邮件激活实体类
 7   * 
 8   * @author Hongten
 9   * 
10   */
11  public class Emailverificationcode implements Serializable {
12  
13      /**
14       * identification number
15  */
16      private static final long serialVersionUID = 6596616450068919832L;
17  
18      /**
19       * id号
20  */
21      private int id;
22  
23      /**
24       * email邮箱
25  */
26      private String email;
27  
28      /**
29       * 密码
30  */
31      private String password;
32      /**
33       * 激活状态,
34  */
35      private int active;
36  
37      public Emailverificationcode() {
38      }
39  
40      public int getId() {
41          return id;
42      }
43  
44      public void setId(int id) {
45          this.id = id;
46      }
47  
48      public String getEmail() {
49          return email;
50      }
51  
52      public void setEmail(String email) {
53          this.email = email;
54      }
55  
56      public String getPassword() {
57          return password;
58      }
59  
60      public void setPassword(String password) {
61          this.password = password;
62      }
63  
64      public int getActive() {
65          return active;
66      }
67  
68      public void setActive(int active) {
69          this.active = active;
70      }
71  
72  }
View Code

/EmailforVerificationCode/src/com/b510/domain/Emailverificationcode.hbm.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2  <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4  <hibernate-mapping>
 5      <class name="com.b510.domain.Emailverificationcode" table="emailverificationcode"
 6          catalog="hrSystem">
 7          <id name="id" type="java.lang.Integer">
 8              <column name="id" />
 9              <generator class="increment" />
10          </id>
11          <property name="email" type="java.lang.String">
12              <column name="email" length="50" />
13          </property>
14          <property name="password" type="java.lang.String">
15              <column name="password" length="50" />
16          </property>
17          <property name="active" type="java.lang.Integer">
18              <column name="active" />
19          </property>
20      </class>
21  </hibernate-mapping>
View Code

/EmailforVerificationCode/src/com/b510/service/EmailVerificationCodeService.java

 1 package com.b510.service;
 2  
 3  import com.b510.domain.Emailverificationcode;
 4  
 5  public interface EmailVerificationCodeService {
 6      // 发件人
 7      static final String FROM_MAIL = "hongtenzoneb@163.com";
 8      // 邮件服务器
 9      static final String SERVER_MAIL = "smtp.163.com";
10      // 邮件主题
11      static final String SUBJECT_MAIL_ACTIVE = "激活邮件";
12      // 邮件主题
13      static final String SUBJECT_MAIL_GETVERIFICATIONCODE = "获取验证码";
14      // 发件人,在邮件的发件人栏目中显示
15      static final String DATAFROM_MAIL = FROM_MAIL;
16      // 登陆邮箱的用户名
17      static final String USER_MAIL = "hongtenzoneb";
18      // 登陆邮箱的密码
19      static final String PASSWORD_MAIL = "***********";
20      /**
21       * 保存一条记录
22       * 
23       * @param emailVerificationCode
24       *            需要被持久化的emailVerificationConde实例
25  */
26      public void save(Emailverificationcode emailVerificationCode);
27  
28      /**
29       * 根据id值获取一条记录
30       * 
31       * @param id
32       *            需要获取记录的id值
33       * @return 对应id值的一条记录
34  */
35      public Emailverificationcode getById(int id);
36  
37      /**
38       * 根据email,password获取一条记录
39       * 
40       * @param email
41       *            电子邮箱
42       * @param password
43       *            密码
44       * @return 根据email,password返回相应值的一条记录
45  */
46      public Emailverificationcode getByEmailAndPassword(String email,
47              String password);
48      /**
49       * 根据email,password,active获取一条记录
50       * 
51       * @param email
52       *            电子邮箱
53       * @param password
54       *            密码
55       * @param active
56       * @return 根据email,password,active返回相应值的一条记录
57  */
58      public Emailverificationcode getByEmailAndPassword(String email,
59              String password,int active);
60  
61      /**
62       * 根据id激活对应的email,active默认为0,激活状态为1
63       * 
64       * @param emailverificationcode
65       *            emailverificationcode一个实例
66       * @return 返回时候激活成功
67  */
68      public int updateActive(Emailverificationcode emailverificationcode);
69      /**
70       * 激活邮箱
71  */
72      public void sendEmail(String toMail,String subject,String content);
73      /**
74       *  定义获取随机字符串方法
75       * @return 返回一个随机字符串
76  */
77      public String getRandomChar(); 
78  }
View Code

/EmailforVerificationCode/src/com/b510/service/impl/EmailVerificationCodeServiceBean.java

  1 package com.b510.service.impl;
  2  
  3  import java.io.IOException;
  4  import java.net.UnknownHostException;
  5  
  6  import com.b510.dao.EmailVerificationCodeDAO;
  7  import com.b510.domain.Emailverificationcode;
  8  import com.b510.service.EmailVerificationCodeService;
  9  import com.b510.utils.MailMessage;
 10  import com.b510.utils.SendEmail;
 11  
 12  public class EmailVerificationCodeServiceBean implements
 13          EmailVerificationCodeService {
 14      /**
 15       * 通过spring的IoC注入EmailVerificationCodeDAO的一个实例
 16  */
 17      private EmailVerificationCodeDAO emailVerificationCodeDAO;
 18  
 19      /**
 20       * 发送邮件的一个实体
 21  */
 22      private SendEmail sendEmail;
 23  
 24      public Emailverificationcode getByEmailAndPassword(String email,
 25              String password) {
 26  
 27          return getEmailVerificationCodeDAO().getByEmailAndPassword(email,
 28                  password);
 29      }
 30      public Emailverificationcode getById(int id) {
 31          return getEmailVerificationCodeDAO().getById(id);
 32      }
 33  
 34      public EmailVerificationCodeDAO getEmailVerificationCodeDAO() {
 35          return emailVerificationCodeDAO;
 36      }
 37  
 38      public SendEmail getSendEmail() {
 39          return sendEmail;
 40      }
 41  
 42      public void save(Emailverificationcode emailVerificationCode) {
 43          getEmailVerificationCodeDAO().save(emailVerificationCode);
 44      }
 45  
 46      public void setEmailVerificationCodeDAO(
 47              EmailVerificationCodeDAO emailVerificationCodeDAO) {
 48          this.emailVerificationCodeDAO = emailVerificationCodeDAO;
 49      }
 50  
 51      public void setSendEmail(SendEmail sendEmail) {
 52          this.sendEmail = sendEmail;
 53      }
 54  
 55      public int updateActive(Emailverificationcode emailverificationcode) {
 56          return getEmailVerificationCodeDAO().updateActive(emailverificationcode);
 57      }
 58      /**
 59       * 激活邮箱
 60  */
 61      public void sendEmail(String toMail,String subject,String content){
 62          MailMessage message = new MailMessage();
 63          message.setFrom(EmailVerificationCodeService.FROM_MAIL);// 发件人
 64          message.setTo(toMail);// 收件人
 65          String server = EmailVerificationCodeService.SERVER_MAIL;// 邮件服务器
 66          message.setSubject(subject);// 邮件主题
 67          message.setContent(content);// 邮件内容
 68          message.setDatafrom(EmailVerificationCodeService.DATAFROM_MAIL);// 发件人,在邮件的发件人栏目中显示
 69          message.setDatato(toMail);// 收件人,在邮件的收件人栏目中显示
 70          message.setUser(EmailVerificationCodeService.USER_MAIL);// 登陆邮箱的用户名
 71          message.setPassword(EmailVerificationCodeService.PASSWORD_MAIL);// 登陆邮箱的密码
 72  
 73          SendEmail smtp;
 74          try {
 75              smtp = new SendEmail(server, 25);
 76              boolean flag;
 77              flag = smtp.sendMail(message, server);
 78              if (flag) {
 79                  System.out.println("邮件发送成功!");
 80              } else {
 81                  System.out.println("邮件发送失败!");
 82              }
 83          } catch (UnknownHostException e) {
 84              e.printStackTrace();
 85          } catch (IOException e) {
 86              e.printStackTrace();
 87          }
 88  
 89          
 90      }
 91      public Emailverificationcode getByEmailAndPassword(String email,
 92              String password, int active) {
 93          return getEmailVerificationCodeDAO().getByEmailAndPassword(email,
 94                  password,active);
 95      }
 96      // 定义获取随机字符串方法
 97      public String getRandomChar() {
 98          // 生成一个0、1、2的随机数字
 99          int rand = (int) Math.round(Math.random() * 2);
100          long itmp = 0;
101          char ctmp = 'u0000';
102          switch (rand) {
103          // 生成大写字母
104          case 1:
105              itmp = Math.round(Math.random() * 25 + 65);
106              ctmp = (char) itmp;
107              return String.valueOf(ctmp);
108              // 生成小写字母
109          case 2:
110              itmp = Math.round(Math.random() * 25 + 97);
111              ctmp = (char) itmp;
112              return String.valueOf(ctmp);
113              // 生成数字
114          default:
115              itmp = Math.round(Math.random() * 9);
116              return itmp + "";
117          }
118      }
119  }
View Code

/EmailforVerificationCode/src/com/b510/utils/MailMessage.java

  1 package com.b510.utils;
  2  
  3  /**
  4   * 邮件信息
  5   * 
  6   * @author Hongten
  7   * 
  8   */
  9  public class MailMessage {
 10      /**
 11       * 发件人
 12  */
 13      private String from;
 14      /**
 15       * 收件人
 16  */
 17      private String to;
 18      /**
 19       * 发件人,在邮件的发件人栏目中显示
 20  */
 21      private String datafrom;
 22      /**
 23       * 收件人,在邮件的收件人栏目中显示
 24  */
 25      private String datato;
 26      /**
 27       * 邮件主题
 28  */
 29      private String subject;
 30      /**
 31       * 邮件内容
 32  */
 33      private String content;
 34      /**
 35       * 发送日期
 36  */
 37      private String date;
 38      /**
 39       * 登陆邮箱的用户名
 40  */
 41      private String user;
 42      /**
 43       * 登陆邮箱的密码
 44  */
 45      private String password;
 46  
 47      /**
 48       * 获取发件人
 49       * 
 50       * @return 发件人
 51  */
 52      public String getFrom() {
 53          return from;
 54      }
 55  
 56      /**
 57       * 设置发件人
 58       * 
 59       * @param from
 60       *            发件人
 61  */
 62      public void setFrom(String from) {
 63          this.from = from;
 64      }
 65  
 66      /**
 67       * 获取收件人
 68       * 
 69       * @return 收件人
 70  */
 71      public String getTo() {
 72          return to;
 73      }
 74  
 75      /**
 76       * 设置收件人
 77       * 
 78       * @param to
 79       *            收件人
 80  */
 81      public void setTo(String to) {
 82          this.to = to;
 83      }
 84  
 85      /**
 86       * 获取发件人,在邮件的发件人栏目中显示
 87       * 
 88       * @return 发件人,在邮件的发件人栏目中显示
 89  */
 90      public String getDatafrom() {
 91          return datafrom;
 92      }
 93  
 94      /**
 95       * 设置发件人,在邮件的发件人栏目中显示
 96       * 
 97       * @param datafrom
 98       *            发件人,在邮件的发件人栏目中显示
 99  */
100      public void setDatafrom(String datafrom) {
101          this.datafrom = datafrom;
102      }
103  
104      /**
105       * 获取收件人,在邮件的收件人栏目中显示
106       * 
107       * @return 收件人,在邮件的收件人栏目中显示
108  */
109      public String getDatato() {
110          return datato;
111      }
112  
113      /**
114       * 设置收件人,在邮件的收件人栏目中显示
115       * 
116       * @param datato
117       *            收件人,在邮件的收件人栏目中显示
118  */
119      public void setDatato(String datato) {
120          this.datato = datato;
121      }
122  
123      /**
124       * 获取邮件主题
125       * 
126       * @return 邮件主题
127  */
128      public String getSubject() {
129          return subject;
130      }
131  
132      /**
133       * 设置邮件主题
134       * 
135       * @param subject
136       *            邮件主题
137  */
138      public void setSubject(String subject) {
139          this.subject = subject;
140      }
141  
142      /**
143       * 获取邮件内容
144       * 
145       * @return 邮件内容
146  */
147      public String getContent() {
148          return content;
149      }
150  
151      /**
152       * 设置邮件内容
153       * 
154       * @param content
155       *            邮件内容
156  */
157      public void setContent(String content) {
158          this.content = content;
159      }
160  
161      /**
162       * 获取发送日期
163       * 
164       * @return 发送日期
165  */
166      public String getDate() {
167          return date;
168      }
169  
170      /**
171       * 设置发送日期
172       * 
173       * @param date
174       *            发送日期
175  */
176      public void setDate(String date) {
177          this.date = date;
178      }
179  
180      /**
181       * 获取登陆邮箱的用户名
182       * 
183       * @return 登陆邮箱的用户名
184  */
185      public String getUser() {
186          return user;
187      }
188  
189      /**
190       * 设置登陆邮箱的用户名
191       * 
192       * @param user
193       *            登陆邮箱的用户名
194  */
195      public void setUser(String user) {
196          this.user = user;
197      }
198  
199      /**
200       * 获取登陆邮箱的密码
201       * 
202       * @return 登陆邮箱的密码
203  */
204      public String getPassword() {
205          return password;
206      }
207  
208      /**
209       * 设置登陆邮箱的密码
210       * 
211       * @param password
212       *            登陆邮箱的密码
213  */
214      public void setPassword(String password) {
215          this.password = password;
216      }
217  
218  }
View Code

/EmailforVerificationCode/src/com/b510/utils/SendEmail.java

  1 package com.b510.utils;
  2  
  3  import java.io.BufferedReader;
  4  import java.io.BufferedWriter;
  5  import java.io.IOException;
  6  import java.io.InputStreamReader;
  7  import java.io.OutputStreamWriter;
  8  import java.net.Socket;
  9  import java.net.SocketException;
 10  import java.net.UnknownHostException;
 11  import java.util.StringTokenizer;
 12  
 13  import sun.misc.BASE64Encoder;
 14  
 15  public class SendEmail {
 16      public SendEmail() {
 17      }
 18  
 19      private boolean debug = true;
 20      BASE64Encoder encode = new BASE64Encoder();// 用于加密后发送用户名和密码
 21  
 22      private Socket socket;
 23  
 24      public SendEmail(String server, int port) throws UnknownHostException,
 25              IOException {
 26          try {
 27              socket = new Socket(server, 25);
 28          } catch (SocketException e) {
 29              System.out.println(e.getMessage());
 30          } catch (Exception e) {
 31              e.printStackTrace();
 32          } finally {
 33              System.out.println("已经建立连接!");
 34          }
 35      }
 36  
 37      // 注册到邮件服务器
 38      public void helo(String server, BufferedReader in, BufferedWriter out)
 39              throws IOException {
 40          int result;
 41          result = getResult(in);
 42  
 43          // 连接上邮件服务后,服务器给出220应答
 44          if (result != 220) {
 45              throw new IOException("连接服务器失败");
 46          }
 47  
 48          result = sendServer("HELO " + server, in, out);
 49  
 50          // HELO命令成功后返回250
 51          if (result != 250) {
 52              throw new IOException("注册邮件服务器失败!");
 53          }
 54      }
 55  
 56      private int sendServer(String str, BufferedReader in, BufferedWriter out)
 57              throws IOException {
 58          out.write(str);
 59          out.newLine();
 60          out.flush();
 61  
 62          if (debug) {
 63              System.out.println("已发送命令:" + str);
 64          }
 65  
 66          return getResult(in);
 67      }
 68  
 69      public int getResult(BufferedReader in) {
 70          String line = "";
 71  
 72          try {
 73              line = in.readLine();
 74              if (debug) {
 75                  System.out.println("服务器返回状态:" + line);
 76              }
 77          } catch (Exception e) {
 78              e.printStackTrace();
 79          }
 80  
 81          // 从服务器返回消息中读出状态码,将其转换成整数返回
 82          StringTokenizer st = new StringTokenizer(line, " ");
 83  
 84          return Integer.parseInt(st.nextToken());
 85      }
 86  
 87      public void authLogin(MailMessage message, BufferedReader in,
 88              BufferedWriter out) throws IOException {
 89          int result;
 90          result = sendServer("AUTH LOGIN", in, out);
 91  
 92          if (result != 334) {
 93              throw new IOException("用户验证失败!");
 94          }
 95          result = sendServer(encode.encode(message.getUser().getBytes()), in,
 96                  out);
 97  
 98          if (result != 334) {
 99              throw new IOException("用户名错误!");
100          }
101          result = sendServer(encode.encode(message.getPassword().getBytes()),
102                  in, out);
103  
104          if (result != 235) {
105              throw new IOException("验证失败!");
106          }
107      }
108  
109      // 开始发送消息,邮件源地址
110      public void mailfrom(String source, BufferedReader in, BufferedWriter out)
111              throws IOException {
112          int result;
113          result = sendServer("MAIL FROM:<" + source + ">", in, out);
114  
115          if (result != 250) {
116              throw new IOException("指定源地址错误");
117          }
118      }
119  
120      // 设置邮件收件人
121      public void rcpt(String touchman, BufferedReader in, BufferedWriter out)
122              throws IOException {
123          int result;
124          result = sendServer("RCPT TO:<" + touchman + ">", in, out);
125  
126          if (result != 250) {
127              throw new IOException("指定目的地址错误!");
128          }
129      }
130  
131      // 邮件体
132      public void data(String from, String to, String subject, String content,
133              BufferedReader in, BufferedWriter out) throws IOException {
134          int result;
135          result = sendServer("DATA", in, out);
136  
137          // 输入date回车后,若收到354应答后,继续输入邮件内容
138          if (result != 354) {
139              throw new IOException("不能发送数据");
140          }
141  
142          out.write("From: " + from);
143          out.newLine();
144          out.write("To: " + to);
145          out.newLine();
146          out.write("Subject: " + subject);
147          out.newLine();
148          out.newLine();
149          out.write(content);
150          out.newLine();
151  
152          // 句点加回车结束邮件内容输入
153          result = sendServer(".", in, out);
154          System.out.println(result);
155  
156          if (result != 250) {
157              throw new IOException("发送数据错误");
158          }
159      }
160  
161      // 退出
162      public void quit(BufferedReader in, BufferedWriter out) throws IOException {
163          int result;
164          result = sendServer("QUIT", in, out);
165  
166          if (result != 221) {
167              throw new IOException("未能正确退出");
168          }
169      }
170  
171      // 发送邮件主程序
172      public boolean sendMail(MailMessage message, String server) {
173          try {
174              BufferedReader in = new BufferedReader(new InputStreamReader(socket
175                      .getInputStream()));
176              BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
177                      socket.getOutputStream()));
178              helo(server, in, out);// helo
179              authLogin(message, in, out);// auth login
180              mailfrom(message.getFrom(), in, out);// mail from
181              rcpt(message.getTo(), in, out);// rcpt to
182              data(message.getDatafrom(), message.getDatato(), message
183                      .getSubject(), message.getContent(), in, out);// DATA
184              quit(in, out);// quit
185          } catch (Exception e) {
186              e.printStackTrace();
187              return false;
188          }
189          return true;
190      }
191  }
View Code

/EmailforVerificationCode/src/struts-email.xml

<?xml version="1.0" encoding="GBK"?>
     <!-- 指定Struts2配置文件的DTD信息 -->
 <!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
     "http://struts.apache.org/dtds/struts-2.1.7.dtd">
     <!-- Struts2配置文件的根元素 -->
 <struts>
     <package name="default" extends="struts-default">
         <!-- 定义处理注册请求的Action,注册完成后,进入登录页面 -->
         <action name="register" class="registerAction">
             <result name="login">/WEB-INF/content/registerSuccess.jsp</result>
             <result name="register">/WEB-INF/content/register.jsp</result>
         </action>
 
         <!-- 定义处理登录系统的的Action -->
         <action name="activeEmail" class="activeEmailAction">
             <!-- 邮箱激活 -->
             <result name="active">/WEB-INF/content/active.jsp</result>
         </action>
 
         <action name="login" class="emailVerificationCodeAction"
             method="login">
             <result name="login">/WEB-INF/content/login.jsp</result>
         </action>
 
         <action name="processLogin" class="emailVerificationCodeAction">
             <!-- 输入验证码页面 -->
             <result name="input">/WEB-INF/content/loginInputVerCode.jsp</result>
             <!-- email没有激活的时候,请重新登录 -->
             <result name="error">/WEB-INF/content/error.jsp</result>
         </action>
 
         <action name="verCode" class="emailVerificationCodeAction"
             method="inputVerificationCode">
             <!-- 验证码验证失败 -->
             <result name="errorVerCode">/WEB-INF/content/errorVerCode.jsp</result>
             <!-- 登录成功界面 -->
             <result>/WEB-INF/content/welcome.jsp</result>
         </action>
     </package>
 </struts>
View Code

/EmailforVerificationCode/src/struts.xml

 1 <?xml version="1.0" encoding="GBK"?>
 2  <!-- 指定Struts2配置文件的DTD信息 -->
 3  <!DOCTYPE struts PUBLIC
 4      "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
 5      "http://struts.apache.org/dtds/struts-2.1.7.dtd">
 6  <!-- Struts2配置文件的根元素 -->
 7  <struts>
 8      <!-- 配置了系列常量 -->
 9      <constant name="struts.custom.i18n.resources" value="resource"/>
10      <constant name="struts.i18n.encoding" value="GBK"/>
11      <constant name="struts.devMode" value="true"/>
12      <include file="struts-email.xml"></include>
13  </struts>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/web.xml

 1 <?xml version="1.0" encoding="GBK"?>
 2  <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 4      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 5      version="3.0">
 6  
 7      <!-- 配置Spring配置文件的位置 -->
 8      <context-param>
 9          <param-name>contextConfigLocation</param-name>
10          <param-value>/WEB-INF/applicationContext.xml</param-value>
11      </context-param>
12      <!-- 使用ContextLoaderListener初始化Spring容器 -->
13      <listener>
14          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15      </listener>
16  
17      <!-- 定义Struts 2的核心Filter -->
18      <filter>
19          <filter-name>struts2</filter-name>
20          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
21      </filter>
22      <!-- 让Struts 2的核心Filter拦截所有请求 -->
23      <filter-mapping>
24          <filter-name>struts2</filter-name>
25          <url-pattern>/*</url-pattern>
26      </filter-mapping>
27  
28      <!-- 定义Web应用的首页 -->
29      <welcome-file-list>
30          <welcome-file>index.jsp</welcome-file>
31      </welcome-file-list>
32  </web-app>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/applicationContext.xml

 1 <?xml version="1.0" encoding="GBK"?>
 2      <!-- 指定Spring配置文件的Schema信息 -->
 3  <beans xmlns="http://www.springframework.org/schema/beans"
 4      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 5      xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
 6      xsi:schemaLocation="http://www.springframework.org/schema/beans 
 7      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 8      http://www.springframework.org/schema/tx 
 9      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
10      http://www.springframework.org/schema/aop 
11      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
12  
13      <bean id="sendEmail" class="com.b510.utils.SendEmail"></bean>
14  
15  
16      <!-- 配置数据源 -->
17      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
18          destroy-method="close">
19          <property name="driverClassName" value="org.gjt.mm.mysql.Driver" />
20          <property name="url" value="jdbc:mysql://localhost:3307/hrSystem" />
21          <property name="username" value="root" />
22          <property name="password" value="root" />
23          <!-- 连接池启动时的初始值 -->
24          <property name="initialSize" value="1" />
25          <!-- 连接池的最大值 -->
26          <property name="maxActive" value="300" />
27          <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
28          <property name="maxIdle" value="2" />
29          <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
30          <property name="minIdle" value="1" />
31      </bean>
32  
33      <bean id="sessionFactory"
34          class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
35          <!-- 配置SessionFactory所需的数据源,注入上面定义的dataSource -->
36          <property name="dataSource" ref="dataSource" />
37  
38          <!-- mappingResources属性用来列出全部映射文件 -->
39          <property name="mappingResources">
40              <list>
41                  <!-- 配置所有PO映射文件 -->
42                  <value>com/b510/domain/Emailverificationcode.hbm.xml</value>
43              </list>
44          </property>
45  
46          <!-- 定义hibernate的SessionFactory的属性 -->
47          <property name="hibernateProperties">
48              <value>
49                  hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
50                  hibernate.hbm2ddl.auto=update
51                  hibernate.show_sql=true
52                  hibernate.format_sql=true
53                  hibernate.cache.use_second_level_cache=true
54                  hibernate.cache.use_query_cache=false
55                  hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
56              </value>
57          </property>
58      </bean>
59  
60      <!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->
61      <!-- 该类是PlatformTransactionManager接口对采用Hibernate的特定实现类 -->
62      <bean id="txManager"
63          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
64          <property name="sessionFactory" ref="sessionFactory" />
65      </bean>
66  
67      <bean id="emailVerificationCodeDAO" class="com.b510.dao.impl.EmailVerificationCodeDAOImpl">
68          <property name="sessionFactory" ref="sessionFactory"></property>
69      </bean>
70  
71      <bean id="emailVerificationCodeService" class="com.b510.service.impl.EmailVerificationCodeServiceBean">
72          <property name="emailVerificationCodeDAO" ref="emailVerificationCodeDAO"></property>
73          <property name="sendEmail" ref="sendEmail"></property>
74      </bean>
75  
76  
77      <bean id="registerAction" class="com.b510.action.RegisterAction">
78          <property name="emailVerificationCodeService" ref="emailVerificationCodeService"></property>
79          <property name="url"
80              value="http://10.5.116.39:1000/EmailforVerificationCode/activeEmail"></property>
81      </bean>
82  
83      <bean id="emailVerificationCodeAction" class="com.b510.action.EmailVerificationCodeAction">
84          <property name="emailVerificationCodeService" ref="emailVerificationCodeService"></property>
85      </bean>
86  
87      <bean id="activeEmailAction" class="com.b510.action.ActiveEmailAction">
88          <property name="emailVerificationCodeService" ref="emailVerificationCodeService"></property>
89      </bean>
90  
91  </beans>
View Code

/EmailforVerificationCode/WebRoot/index.jsp

<jsp:forward page="/WEB-INF/content/login.jsp"/>

/EmailforVerificationCode/WebRoot/WEB-INF/content/login.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3  <%@taglib prefix="s" uri="/struts-tags"%>
 4  <html>
 5  <head>
 6  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 7  <title>登录系统</title>
 8  <s:head/>
 9  </head>
10  <body>
11  <table width="780" align="center">
12  <tr>
13  <td>
14  请输入邮箱和密码来登录,如果还没有注入,请点击这里进行<a href="register.action">注册</a><br />
15  <div align="center">
16  <s:form action="processLogin.action">
17      <s:textfield name="email" label="邮箱"/>
18      <s:textfield name="password" label="密码"/>
19      <tr><td colspan="2">
20      <s:submit value="登录" theme="simple"/><s:reset  theme="simple" value="重填"/>
21      </td></tr>
22  </s:form>
23  </div>
24  </td>
25  </tr>
26  </table>
27  </body>
28  </html>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/content/register.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 3      "http://www.w3.org/TR/html4/loose.dtd">
 4  <%@taglib prefix="s" uri="/struts-tags"%>
 5  <html>
 6  <head>
 7  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 8  <title>注册信息</title>
 9  <s:head/>
10  </head>
11  <body>
12  <table width=780 align="center">
13  <tr>
14  <td>
15  注册信息:<br>
16  <div align="center">
17  <s:form action="register">
18      <s:textfield name="email" label="邮箱"/>
19      <s:textfield name="password" label="密码"/>
20      <s:token/>
21      <tr><td colspan="2">
22      <s:submit value="注册" theme="simple"/>
23      <s:reset  theme="simple" value="重设"/>
24      </td></tr>
25  </s:form>
26  </div>
27  </td>
28  </tr>
29  </table>
30  </body>
31  </html>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/content/registerSuccess.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3  <html>
 4  <head>
 5     <title>欢迎登录</title>
 6      <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 7  </head>
 8  <body>
 9  恭喜你,注册成功了!系统会发一封邮件到你注册的邮箱,<br />
10  请打开你注册的邮箱,激活你注册的邮箱。
11  </body>
12  </html>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/content/active.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3  <html>
 4  <head>
 5     <title>激活页面</title>
 6      <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 7  </head>
 8  <body>
 9  你的邮箱已经激活,你现在可以进行<a href="login.action">登录操作</a>10  </body>
11  </html>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/content/loginInputVerCode.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3  <%@taglib prefix="s" uri="/struts-tags"%>
 4  <html>
 5  <head>
 6  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 7  <title>登录系统-输入验证码</title>
 8  <s:head/>
 9  </head>
10  <body>
11  <table width="780" align="center">
12  <tr>
13  <td>
14  你会在你注册的邮箱中收到一封邮件,里面有验证码,请输入验证码完成登录<br />
15  <div align="center">
16  <s:form action="verCode">
17      <s:textfield name="verificationCode" label="验证码"/>
18      <tr><td colspan="2">
19      <s:submit value="提交" theme="simple"/><s:reset  theme="simple" value="重填"/>
20      </td></tr>
21  </s:form>
22  </div>
23  </td>
24  </tr>
25  </table>
26  </body>
27  </html>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/content/error.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3 <html>
 4 <head>
 5    <title>出错提示页</title>
 6     <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 7 </head>
 8 <body>
 9 你的邮箱可能未激活,请进入你的邮箱进行激活!谢谢
10 </body>
11 </html>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/content/errorVerCode.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3  <html>
 4  <head>
 5     <title>出错提示页</title>
 6      <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 7  </head>
 8  <body>
 9  你输入的验证码有错误!请重新<a href="processLogin.action">登录</a>
10  </body>
11  </html>
View Code

/EmailforVerificationCode/WebRoot/WEB-INF/content/welcome.jsp

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %>
 2  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3  <html>
 4  <head>
 5     <title>欢迎登录</title>
 6      <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 7  </head>
 8  <body>
 9  欢迎登录成功!
10  </body>
11  </html>
View Code

原文作者:http://www.cnblogs.com/hongten/archive/2012/04/04/java_spring_hibernate_struts2.html

源码下载https://files.cnblogs.com/hongten/EmailforVerificationCode.zip

原文地址:https://www.cnblogs.com/lixiaozhe/p/3147777.html