J2EE 之 邮箱激活示例(二)

修改信息:

package com.ethan.accountactivate.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UpdateAccountUI extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.getRequestDispatcher("/WEB-INF/pages/updateAccountUI.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

package com.ethan.accountactivate.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ethan.accountactivate.domain.User;
import com.ethan.accountactivate.utils.EmailUtil;

public class UpdateAccount extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String email = request.getParameter("email");
		User user = (User) request.getSession().getAttribute("user");
		
		user.setEmail(email);
		//冻结账户
		user.setActivated(false);
		user.setRandKey(UUID.randomUUID().toString());
		
		//发送邮件
		try {
			EmailUtil.sendMail(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.getRequestDispatcher("WEB-INF/pages/login.jsp").forward(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

pass.dat文件在com.ethan.accountactivate.utils包下边

package com.ethan.accountactivate.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ethan.accountactivate.domain.User;
import com.ethan.accountactivate.utils.EmailUtil;

public class RenewActivate extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		User user = (User) request.getSession().getAttribute("user");
		try {
			EmailUtil.sendMail(user);
			
			//此处可以转到页面,提示发送成功,根据提供的邮箱后缀,判断是哪个邮箱服务器,给出相应的邮箱连接,让用户进入邮箱去激活
			request.getRequestDispatcher("/WEB-INF/pages/loginUI.jsp").forward(request, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

com.ethan.accountactivate.utils

pass.dat文件在com.ethan.accountactivate.utils包下边,里边是我的126邮箱密码

package com.ethan.accountactivate.utils;

import java.security.MessageDigest;

import javax.servlet.ServletRequest;

import com.ethan.accountactivate.domain.User;

public class AccountActivateUtil {
	/*//假的邮箱  会有漏洞
	public static String generateActivateLink(int userId) {
		//只要知道userId,假邮箱就可以激活。直接输入这个连接
		return "http://localhost:8080/accountActivate/ActivateAccount?id="+userId;
	}*/
	//便于维护,只用改一个地方
	private static final String checkCodeName = "checkCode";
	public static String generateActivateLink(User user) {
		//只要知道userId,假邮箱就可以激活。直接输入这个连接
		String link = "http://localhost:8080/accountActivate/ActivateAccount?id="+user.getId()+"&"+checkCodeName+"="+generateCheckcode(user);
		System.out.println(link);
		return link;
	}
	
	public static boolean verifyCheckcode(ServletRequest request,User user) {
		String checkcode = request.getParameter(checkCodeName);
		return checkcode.equals(generateCheckcode(user));
	}
	private static String generateCheckcode(User user) {
		String password = user.getPassword();
		String randKey = user.getRandKey();
		System.out.println(randKey);
		return md5(password+randKey);
	}

	private static String md5(String string) {
		char[] codes = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		StringBuilder sb = new StringBuilder();
		
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] digest = md.digest(string.getBytes());
			
			for(int i=0;i<digest.length;i++) {
				sb.append(codes[(digest[i]>>4)&0x0f]);
				sb.append(codes[digest[i]&0x0f]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}
	
	
}

package com.ethan.accountactivate.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.ethan.accountactivate.domain.User;


public class EmailUtil {
	public static void sendMail(User user) throws Exception {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		//发送方一定要是126的邮箱
		props.setProperty("mail.host", "smtp.126.com");
		//需要传递用户名和密码
		props.setProperty("mail.smtp.auth", "true");
		Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				InputStream ips = EmailUtil.class.getResourceAsStream("pass.dat");
				BufferedReader bis = new BufferedReader(new InputStreamReader(ips));
				
				try {
					String pass = bis.readLine();
					System.out.println(pass);
					bis.close();
					//126邮箱作为发送方
					return new PasswordAuthentication("qethan@126.com",pass);
				} catch(IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		});
		
		Message msg = new MimeMessage(session);
		//发送人 MimeUtility.encodeText()可以用来编码
		msg.setFrom(InternetAddress.parse("qethan@126.com")[0]);
		//发送内容
		msg.setSubject("ethan 为您发送的激活连接");
		//收信人
		msg.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		//发件日期
		msg.setSentDate(new Date());
		msg.setContent("<a href='"+AccountActivateUtil.generateActivateLink(user)+"'>单击此处激活帐号</a>","text/html;charset=utf-8");
		Transport.send(msg);
	}
}


下边是jsp页面:

/accountActivate/WebRoot/WEB-INF/pages

registerUserUI.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'registerUserUI.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
	<style type="text/css">
		.error {
			color:red;
		}
	</style>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath }/RegisterUser" method="post">
    	用户名:<input type="text" name="userName" value="${param.userName }"><span class="error">${errors.userName}</span><br/>
    	密码:<input type="password" name="password" value="${param.password }"><span class="error">${errors.password}</span><br/>
    	确认密码:<input type="password" name="password2" value="${param.password2 }"><span class="error">${errors.password2}</span><br/>
    	邮箱地址:<input type="text" name="email" value="${param.email }"><span class="error">${errors.email}</span><br/>
    	<input type="submit" name="submit" value="注册"><br/>
    </form>
  </body>
</html>
registerUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'registerUser.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    注册成功,请收邮件以激活您的帐号。如果email有错误,请修改你的账户信息。<br>
  </body>
</html>
loginUI.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'loginUI.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  <!-- 如果session中有user对象 -->
  	<c:if test="${not empty user }"><jsp:forward page="/WEB-INF/pages/login.jsp"/></c:if>
    <form action="${pageContext.request.contextPath }/Login" method="post">
    	用户名:<input type="text" name="userName" value="${param.userName }"><span class="error">${errors.userName}</span><br/>
    	密码:<input type="password" name="password" value="${param.password }"><span class="error">${errors.password}</span><br/>
    	
    	<input type="submit" name="submit" value="登录"><br/>
    </form>
  </body>
</html>
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    ${user.name }${user.activated?"已激活":"未激活" } <br>
    <c:if test="${not user.activated }">
    	请进入你的邮箱激活账户,如果的你的激活邮件已丢失,请<a href="${pageContext.request.contextPath }/RenewActivate">重新获取激活邮件</a>
    	如果你原先填写的email地址无法接收到激活邮件,请修改邮箱地址,再去激活。<a href="${pageContext.request.contextPath }/UpdateAccountUI">修改邮箱</a>
    </c:if>
  </body>
</html>

updateAccount.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'updateAccountUI.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <form action="${pageContext.request.contextPath }/UpdateAccount" method="post">
    	用户名:<input type="text" name="userName" value="${user.name }" readonly><br/>
    
    	邮箱地址:<input type="text" name="email" value="${user.email }"><span class="error">${errors.email}</span><br/>
    	<input type="submit" name="submit" value="修改"><br/>
    </form>
  </body>
</html>

web.xml 中
<servlet-mapping>
    <servlet-name>RegisterUserUI</servlet-name>
    <url-pattern>/RegisterUserUI</url-pattern>

.....

我这里用首字母大写了/RegisterUserUI,还是首小写看着爽,这里就不改了。测试过了,没有问题!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值