Java登録時にアクティブ化メールとアクティブ化を送信する実装例

10290 ワード

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    ,        ,        ,     !");
    sb.append("http://localhost:8080/springmvc/user/register?action=activate&email=");
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("      (       )!"); 
    } 
 
  }
}
  

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 = "[email protected]";//    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


Email:
register_success.jsp


         !             !
 

activate_success.jsp:


        ,       !
 

activate_failure.jsp:


      !    :${message }


以上がJava登録時にアクティブ化メールとアクティブ化を送信する簡単な例ですが、質問があればコメントして議論し、共に進歩してください.java開発に関する文章は当駅にはたくさんあります.
皆さんを歓迎して、検索して参照して、みんなの当駅に対する支持に感謝します!