欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 注册时发送激活邮件和激活的实现示例

程序员文章站 2023-12-03 18:12:34
java 注册时发送激活邮件和激活的实现示例 最近从项目分离出来的注册邮箱激活功能,整理一下,方便下次使用 1.registercontroller.java...

java 注册时发送激活邮件和激活的实现示例

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

1.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");
    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;
  }
  
}
 

2.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;
 
@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("该邮箱未注册(邮箱地址不存在)!"); 
    } 
 
  }
}
  

3.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();
  }
 
}

4.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;
 
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();
    }
  }
}

5.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>

以上就是java 注册时发送激活邮件和激活的简单实例,如有疑问请留言讨论,共同进步,关于java开发的文章本站还有很多,

欢迎大家,搜索参阅,谢谢大家对本站的支持!