您好,登錄后才能下訂單哦!
利用Java怎么實現一個郵箱激活功能?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
實現思路
注冊時填寫郵箱,點擊注冊時網站系統郵箱發送激活驗證鏈接到此郵箱,用戶來激活賬戶
點擊注冊,系統郵箱會發送一封激活郵件到你填寫的郵箱賬號中
在沒有進行激活操作前,設定某個字段狀態是0,表示此賬號未激活,不可以使用或者某些功能受限
激活操作之后,將activated字段更新為1,這樣就完成了激活操作
那么這里還有一個codeUrl字段,他的作用是存入一個唯一標識的隨機碼,這個隨機碼由用戶名和UUID唯一標識的隨機數組成,這樣做的目的是防止用戶使用不存在的郵箱又修改鏈接中的參數來激活賬戶,將鏈接中的隨機碼和數據庫中的比對,來達到相對安全的激活。
下面是具體的代碼
首先是注冊的servlet,這里主要測試激活賬號的功能,注冊代碼有點low,不安全,將就看一下
package org.amuxia.emailtest.servlet; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.amuxia.emailtest.pojo.User; import org.amuxia.emailtest.utils.EmailUtils; import org.amuxia.emailtest.utils.MyJDBC; /** * @author amuxia * 2017年7月24日 */ @WebServlet("/RegistServlet") public class RegistServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); String codeUrl = UUID.randomUUID().toString(); User user = new User(); user.setUsername(username); user.setPassword(password); user.setEmail(email); user.setActivated(false); //剛注冊默認是沒有激活狀態 String SQL = "insert into tb_user(username,password,email,activated,codeUrl) value (?,?,?,?,?) "; MyJDBC.insert(SQL, false, username,password,email,0,codeUrl);//注冊信息插入數據庫 String querySQL = "select * from tb_user where email=?"; ResultSet rs = MyJDBC.query(querySQL, email); try { if(rs.next()){ user.setId(rs.getInt(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 注冊成功后,發送帳戶激活鏈接 request.getSession().setAttribute("user", user); EmailUtils.sendAccountActivateEmail(user); request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response); } }
激活賬號的Servlet,也就是更新操作
package org.amuxia.emailtest.servlet; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.amuxia.emailtest.pojo.User; import org.amuxia.emailtest.utils.GenerateLinkUtils; import org.amuxia.emailtest.utils.MyJDBC; /** * @author amuxia * 2017年7月24日 */ @WebServlet("/ActivateServlet") public class ActivateServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String idValue = request.getParameter("id"); System.out.println(idValue); int id = -1; try { id = Integer.parseInt(idValue); } catch (NumberFormatException e) { e.printStackTrace(); } String SQL = "select * from tb_user where id=?"; ResultSet rs= MyJDBC.query(SQL, id); User user = new User(); try { if(rs.next()){ user.setId(rs.getInt(1)); user.setUsername(rs.getString(2)); user.setPassword(rs.getString(3)); user.setEmail(rs.getString(4)); user.setActivated(rs.getBoolean(5)); user.setCodeUrl(rs.getString(6)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //驗證無誤,狀態更改為1,即激活 if(GenerateLinkUtils.verifyCheckcode(user, request)){ String updSQL = "update tb_user set activated =1 where id=?"; MyJDBC.execute(updSQL, id); user.setActivated(true); request.getSession().setAttribute("user", user); request.getRequestDispatcher("/WEB-INF/jsp/pass.jsp").forward(request, response); } } }
發送Email的工具類
package org.amuxia.emailtest.utils; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.amuxia.emailtest.pojo.User; /** * @author amuxia * 2017年7月24日 */ public class EmailUtils { private static final String FROM = "要發送郵件的郵箱,這個例子是163郵箱"; public static void sendAccountActivateEmail(User user) { Session session = getSession(); MimeMessage message = new MimeMessage(session); try { message.setSubject("這是一封激活賬號的郵件,復制鏈接到地址欄來激活他"); message.setSentDate(new Date()); message.setFrom(new InternetAddress(FROM)); message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); message.setContent("<a target='_BLANK' href=''>"+GenerateLinkUtils.generateActivateLink(user)+"</a>","text/html;charset=utf-8"); Transport.send(message); } catch (Exception e) { e.printStackTrace(); } } public static Session getSession() { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.host", "smtp.163.com"); props.setProperty("mail.smtp.port", "25"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(FROM, "上面郵箱的密碼"); } }); return session; } }
這里需要注意一下,以上例子配置的是163郵箱,需要進行郵箱客戶端的授權,授權之后,網易郵箱會發來一份客戶端授權碼作為替代郵箱密碼,代碼里填寫的密碼其實是授權碼,配置好郵箱最好發一份郵件測試一下,有時程序出問題很可能是郵箱客戶端根本發不了郵件
加密賬戶激活鏈接生成的工具類
package org.amuxia.emailtest.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.servlet.ServletRequest; import org.amuxia.emailtest.pojo.User; /** * @author amuxia * 2017年7月24日 */ public class GenerateLinkUtils { private static final String CHECK_CODE = "checkCode"; public static String generateActivateLink(User user) { return "http://localhost/EmailDemo/ActivateServlet?id=" + user.getId() + "&" + CHECK_CODE + "=" + generateCheckcode(user); } /** * 生成校驗碼,用戶名+UUID唯一標識符,為安全把他們加密發送 * @param user * @return */ public static String generateCheckcode(User user) { String userName = user.getUsername(); String randomCode = user.getCodeUrl(); return md5(userName + ":" + randomCode); } /** * 接收回來的校驗碼和發送出去的是不是同一份 * @param user * @param request * @return */ public static boolean verifyCheckcode(User user,ServletRequest request) { String checkCode = request.getParameter(CHECK_CODE); System.out.println(generateCheckcode(user).equals(checkCode)); return true; } private static String md5(String string) { MessageDigest md = null; try { md = MessageDigest.getInstance("md5"); md.update(string.getBytes()); byte[] md5Bytes = md.digest(); return bytes2Hex(md5Bytes); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("md5這里出錯了"); } return null; } private static String bytes2Hex(byte[] byteArray) { StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if(byteArray[i] >= 0 && byteArray[i] < 16) { strBuf.append("0"); } strBuf.append(Integer.toHexString(byteArray[i] & 0xFF)); } return strBuf.toString(); } }
還有一個操作數據庫的封裝類,MyJDBC,前面博客有寫,代碼挺長,就不貼了,這是鏈接:
https://www.jb51.net/article/70107.htm
https://www.jb51.net/article/88647.htm
實體類User
package org.amuxia.emailtest.pojo; public class User { private int id; private String username; private String password; private String email; private boolean activated;//賬號狀態 private String codeUrl;//激活鏈接中的隨機碼 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } 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 boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getCodeUrl() { return codeUrl; } public void setCodeUrl(String codeUrl) { this.codeUrl = codeUrl; } public User() { super(); } }
注冊的jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>注冊</title> </head> <body> <form action="/EmailDemo/RegistServlet" method="post"> 用戶名:<input type="text" name="username"><br/> 密碼:<input type="password" name="password"><br/> 郵箱:<input type="text" name="email"><br/> <input type="submit" value="注冊"> </form> </body> </html>
用到的包?
關于利用Java怎么實現一個郵箱激活功能問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。