----------------------------------------------------------------------------------------------
[版權申明:本文系做者原創,轉載請註明出處]
文章出處:http://blog.csdn.net/sdksdk0/article/details/52144698
做者:朱培 ID:sdksdk0 郵箱: zhupei@tianfang1314.cn html
--------------------------------------------------------------------------------------------java
本文主要內容是分享用戶註冊時須要進行的郵箱激活功能的實現。在咱們都知道在一個網站中,用戶註冊後須要來一個郵箱進行激活是很常見的功能,那麼咱們今天就來學習一下這個郵箱驗證功能.這裏以個人一個小項目「網上書店」的這個模塊來講明這個郵箱激活的功能!採用的是mvc模式開發!mysql
首先咱們須要對用戶註冊的表進行設計,裏面要添加激活碼的字段和激活的狀態的字段。咱們能夠看到頁面是這樣的,有5個須要填寫的字段,而後加上咱們這個激活碼的就有7個了。git
這裏我採用的是mysql數據庫。actived表示激活碼的狀態位,0表示未激活,1表示激活了.github
CREATE TABLE customers( id VARCHAR(100) PRIMARY KEY, username VARCHAR(100) NOT NULL UNIQUE, PASSWORD VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT NULL UNIQUE, address VARCHAR(255) NOT NULL , email VARCHAR(50) NOT NULL UNIQUE, CODE VARCHAR(200) UNIQUE, --激活碼 actived BIT(1) --激活碼的狀態位,0表示未激活,1表示激活 )
新建一個Customer.javaweb
生成其get\set方法便可。sql
private String id; private String username; private String password; private String phone; private String address; private String email; private String code; //激活碼 private boolean actived; //帳戶是否激活
新建一個CustomerDao.java數據庫
有保存密碼、更新激活狀態、登陸等。session
public interface CustomerDao { void save(Customer customer); void update(Customer customer); Customer findByCode(String code); Customer find(String username, String password); }
接口的實現類mvc
CustomerDaoImpl.java
咱們主要就是在這個裏面進行與數據庫的交互
public class CustomerDaoImpl implements CustomerDao { private QueryRunner qr=new QueryRunner(C3P0Util.getDataSource()); public void save(Customer customer) { try { qr.update("insert into customers (id,username,password,phone,address,email,code,actived) values (?,?,?,?,?,?,?,?)", customer.getId(),customer.getUsername(),customer.getPassword(),customer.getPhone(),customer.getAddress(), customer.getEmail(),customer.getCode(),customer.isActived()); } catch (SQLException e) { throw new RuntimeException(e); } } public void update(Customer customer) { try { qr.update("update customers set username=?,password=?,phone=?,address=?,email=?,code=?,actived=? where id=?", customer.getUsername(),customer.getPassword(),customer.getPhone(),customer.getAddress(), customer.getEmail(),customer.getCode(),customer.isActived(),customer.getId()); } catch (SQLException e) { throw new RuntimeException(e); } } public Customer findByCode(String code) { try { return qr.query("select * from customers where code=?", new BeanHandler<Customer>(Customer.class),code); } catch (SQLException e) { throw new RuntimeException(e); } } public Customer find(String username, String password) { try { return qr.query("select * from customers where username=? and password=?", new BeanHandler<Customer>(Customer.class),username,password); } catch (SQLException e) { throw new RuntimeException(e); } } }
新建一個service類:接口BusinessService.java
//用戶註冊 void registCustomer(Customer customer); //根據激活碼獲取用戶信息 Customer findByCode(String code); //激活客戶的帳戶 void activeCustomer(Customer customer); //根據用戶名或密碼登陸,若是帳戶沒有激活就返回null Customer login(String username,String password);
接口的實現
@Override public void registCustomer(Customer customer) { customer.setId(UUID.randomUUID().toString()); customerDao.save(customer); } @Override public Customer findByCode(String code) { return customerDao.findByCode(code); } @Override public void activeCustomer(Customer customer) { if(customer==null) throw new RuntimeException("數據不能爲空"); if(customer.getId()==null) throw new RuntimeException("更新數據的主鍵不能爲空"); customerDao.update(customer); } @Override public Customer login(String username, String password) { Customer customer = customerDao.find(username,password); if(customer==null) return null; if(!customer.isActived()) return null; return customer; }
這裏是控制層:激活郵箱我使用的是在另外的一個線程中實現的。SendMailThread.java中實現。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String op=request.getParameter("op"); if("customerRegist".equals(op)){ customerRegist(request,response); }else if("activeCustomer".equals(op)){ activeCustomer(request,response); }else if("login".equals(op)){ login(request,response); }else if("logout".equals(op)){ logout(request,response); } } //註銷登陸 private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException { request.getSession().removeAttribute("customer"); response.getWriter().write("註銷成功!2秒後轉向主頁"); response.setHeader("Refresh", "2;URL="+request.getContextPath()); } //用戶登陸 private void login(HttpServletRequest request, HttpServletResponse response) throws IOException { String username=request.getParameter("username"); String password=request.getParameter("password"); Customer customer=s.login(username, password); if(customer==null){ response.getWriter().write("錯誤的用戶名或密碼,或者您的帳戶尚未激活!5秒後轉向登錄頁"); response.setHeader("Refresh", "5;URL="+request.getContextPath()+"/login.jsp"); return; } request.getSession().setAttribute("customer", customer); response.getWriter().write("登錄成功!2秒後轉向主頁"); response.setHeader("Refresh", "2;URL="+request.getContextPath()); } //激活郵箱 private void activeCustomer(HttpServletRequest request, HttpServletResponse response) throws IOException { String code=request.getParameter("code"); Customer customer=s.findByCode(code); if(customer==null){ response.getWriter().write("發生未知錯誤,請從新輸入"); return ; } customer.setActived(true); s.activeCustomer(customer); response.getWriter().write("激活成功!2秒後轉向主頁"); response.setHeader("Refresh", "2;URL="+request.getContextPath()); } //新用戶註冊,發送激活郵件 private void customerRegist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //封裝數據 Customer customer=WebUtil.fillBean(request,Customer.class); customer.setCode(UUID.randomUUID().toString()); //發送郵件,單獨啓動一個線程 SendMailThread smt=new SendMailThread(customer); smt.start(); s.registCustomer(customer); request.setAttribute("message", "註冊成功,咱們已經發送了一封激活郵件到您的"+customer.getEmail()+"中,請及時激活您的帳戶"); request.getRequestDispatcher("/message.jsp").forward(request, response); }
咱們剛纔將其抽取到一個線程中來實現.我這裏使用的是萬網的mail.host,因此其屬性值爲smtp.mxhichina.com,若是你用的是163郵箱的話,就替換爲smtp.163.com便可。
對於下面點擊激活後跳轉的網址爲你的工程的名字,這個能夠根據實際狀況配置,也能夠直接引入公網域名來使用。
<a href='http://localhost:8080/BookStore/servlet/ClientServlet?op=activeCustomer&code="+customer.getCode()+"'>激活</a>
public class SendMailThread extends Thread{ private Customer customer; public SendMailThread(Customer customer){ this.customer=customer; } public void run(){ Properties props=new Properties(); props.setProperty("mail.transport.protocol", "smtp");//規範規定的參數 props.setProperty("mail.host", "smtp.mxhichina.com");//這裏使用萬網的郵箱主機 props.setProperty("mail.smtp.auth", "true");//請求認證,不認證有可能發不出去郵件。 Session session=Session.getInstance(props); MimeMessage message=new MimeMessage(session); try { message.setFrom(new InternetAddress("xingtian@tianfang1314.cn")); //這裏能夠根據你的實際狀況更改郵箱號 message.setRecipients(Message.RecipientType.TO, customer.getEmail()); message.setSubject("來自指令匯科技書店的註冊郵件"); message.setContent("","text/html;charset=UTF-8"); message.setContent("親愛的"+customer.getUsername()+":<br/>請猛戳下面激活您的帳戶<a href='http://localhost:8080/BookStore/servlet/ClientServlet?op=activeCustomer&code="+customer.getCode()+"'>激活</a><br/>", "text/html;charset=UTF-8"); message.saveChanges(); Transport ts = session.getTransport(); ts.connect("你的郵箱帳號", "郵箱密碼"); ts.sendMessage(message, message.getAllRecipients()); ts.close(); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
7、界面
關於註冊的這個界面我是真的不寫了,其實就是一個表單而已,裏面經過一個servlet轉向那個servlet就能夠了。記得去web.xml中配置一個servlet,或者你直接用註解也是能夠的。
<form action="${pageContext.request.contextPath}/servlet/ClientServlet?op=customerRegist" method="post">
效果以下: