Java registered mailbox activation validation implementation code

  • 2020-04-01 02:38:10
  • OfStack

Recently separated from the project registered email activation function, tidy up, convenient for the next use

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);
        /// if it's safe, you can make the activation code a little more complicated, so I'll make it a little easier here
        //user.setValidateCode(MD5Tool.MD5Encrypt(email));
        user.setValidateCode(MD5Util.encode2hex(email));

        userDao.save(user);//Save registration information

        /// the contents of the email
        StringBuffer sb=new StringBuffer(" Click the link below to activate the account, 48 The link can only be used once. Please activate it as soon as possible! </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>");

        //Send E-mail
        SendEmail.send(email, sb.toString());
        System.out.println("Send E-mail");

    }

    
      /// pass the activation code and email
    public void processActivate(String email , String validateCode)throws ServiceException, ParseException{  
         //Data access layer, access to user information via email
        UserModel user=userDao.find(email);
        //Verify that the user exists
        if(user!=null) {  
            //Verify user activation status & NBSP;
            if(user.getStatus()==0) { 
                /// no activation
                Date currentTime = new Date();//Getting the current time & NBSP;
                //Verify that the link is expired
                currentTime.before(user.getRegisterTime());
                if(currentTime.before(user.getLastActivateTime())) {  
                    //Verify that the activation code is correct & NBSP;
                    if(validateCode.equals(user.getValidateCode())) {  
                        // Successful activation,  // And update the active state of the user as activated  
                        System.out.println("==sq==="+user.getStatus());
                        user.setStatus(1);//Change the state to active
                        System.out.println("==sh==="+user.getStatus());
                        userDao.update(user);
                    } else {  
                       throw new ServiceException(" The activation code is incorrect ");  
                    }  
                } else { throw new ServiceException(" Activation code expired! ");  
                }  
            } else {
               throw new ServiceException(" The mailbox has been activated, please log in! ");  
            }  
        } else {
            throw new ServiceException(" This mailbox is not registered (the mailbox address does not exist)! ");  
        }  

    } 
}

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");
        System.out.println("-----r----"+action);
        ModelAndView mav=new ModelAndView();
        if("register".equals(action)) {
            //registered
            String email = request.getParameter("email");
            service.processregister(email);//Email activation
            mav.addObject("text","registered successful ");
            mav.setViewName("register/register_success");
        } 
        else if("activate".equals(action)) {
            //The activation
            String email = request.getParameter("email");//Access to email
            String validateCode = request.getParameter("validateCode");//The activation code 

            try {
                service.processActivate(email , validateCode);// call The activation methods 
                mav.setViewName("register/activate_success");
            } catch (ServiceException e) {
                request.setAttribute("message" , e.getMessage());
                mav.setViewName("register/activate_failure");
            }

        }
        return mav;
    }
    
}

Userdao.java (here the individual did not do the warehousing operation, just use the collection, did the effect out 0_0)


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;

@Repository
public class UserDao {

   public HashMap<String, String> map=new HashMap<String, String>();
    /**
     * @ Save registration information 
     *  private Long id;
        private String name;
        private String password;
        private String email;//Registered account
        private int status;//active
        private String validateCode;//Activation code
        private Date  registerTime;//Registration time
     */
    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);

    }

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

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

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;//Registered account
 private int status=0;//active
 private String validateCode;//Activation code
 private Date  registerTime;//Registration time

    
    /////////////////
    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


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";//Sender's email
    public static final String PWD = "123456";//Sender password

    
    private static Session getSession() {
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);//Set the server address
        props.put("mail.store.protocol" , PROTOCOL);//The protocol
        props.put("mail.smtp.port", PORT);//Set 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(" Account activation email ");
            msg.setSentDate(new Date());
            msg.setContent(content , "text/html;charset=utf-8");

            //Send the message
            Transport.send(msg);
        }
        catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

MD5Util. Java


package com.app.tools;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {

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

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

 
 public static boolean validate(String unknown , String okHex) {
  return okHex.equals(encode2hex(unknown));
 }

}

ServiceException. Java


package com.app.tools;
public class ServiceException extends Exception {
 private static final long serialVersionUID = -1708015121235851228L;

 public ServiceException(String message) {
  super(message);
 }
}

The JSP page

RegisterEmailValidae. JSP


   <h2> Registration activation </h2>
    <form action="user/register?action=register" method="post">
        Email:<input type="text" id="email" name="email" value="" >
        <input type="submit" value=" submit ">
    </form>

Register_success. JSP


  <body>
     Congratulations! Please go to the registered email and click the link to activate! 
  </body>

Activate_success. JSP:


 <body>
     Account activation successful, click here to log in! 
  </body>

activate_failure.jsp:
<body>
     Activation failed! Error message: ${message }
  </body>

Effect:
1
< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/20131227154957234.jpg" >

2

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/20131227155045112.jpg" >

3

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/20131227155123799.jpg" >

4

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/20131227155201681.jpg" >

5

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/20131227155227580.jpg" >


Related articles: