Java實現註冊時發送啟用郵件+啟用

來源:互聯網
上載者:User

標籤:highlight   har   註冊帳號   factor   resource   prot   default   date()   param   

最近從項目分離出來的註冊郵箱啟用功能,整理一下,方便下次使用

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;@Controllerpublic 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;@Servicepublic 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 = "[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

<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實現註冊時發送啟用郵件+啟用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.