利用Servlet实现用户永久登录

在Servlet中通过Cookie技术实现,在Servlet中输入用户账号,密码和有效期,将账号信息保存在Cookie中,设置Cookie的最大保存时间,将此Cookie保存在客户端的Cookie中

使用MD5加密技术,通过MD5加密技术将用户账号生成一个密钥并保存在Cookie中,然后再用户登录中,根据该密钥来判断用户显示的是用户登录还是登陆后的状态。MD5加密技术通过java.security.Message.Digest类实现的
在这里插入图片描述
在这里插入图片描述
MakeMD5类,加密

import java.security.MessageDigest;

public class MakeMD5 {
	public final static String getMD5(String str){
		char hexDiagitArr[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
		MessageDigest digest=null;
		try{
			digest=MessageDigest.getInstance("MD5");	//创建MD5算法摘要
			digest.update(str.getBytes());				//更新摘要
			byte mdBytes[]=digest.digest();				//加密并返回字节数组
			//新建字符数组,长度为myBytes字节数组的2倍,用于保存加密后的值
			char newCArr[]=new char[mdBytes.length*2];
			int k=0;
			for(int i=0;i<mdBytes.length;i++){			//循环字符串组
				byte byte0=mdBytes[i];					//获得每一个字节
				newCArr[k++]=hexDiagitArr[byte0>>>4&0xf];
				newCArr[k++]=hexDiagitArr[byte0&0xf];
			}
			return String.valueOf(newCArr);		//返回加密后的字符串
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
}

index.jsp页面,第一次访问显示登陆页面,第二次访问判断Servlet返回的Cookie信息,根据Cookie信息来决定是否显示用户登录之后的信息

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

<%
	boolean loginFlag = false;					//设置一个变量 ,用于保存是否登录
	String account = null ;						//声明用于保存从Cookie中读取的账号
	String md5Account = null;					//声明用于保存从Cookie中读取的加密的账号 
	Cookie cookieArr[] = request.getCookies(); 	//获取请求中所有的Cookie
	if(cookieArr!=null&&cookieArr.length>0){
		for(Cookie cookie : cookieArr){			//循环Cookie数组
			if(cookie.getName().equals("account")){
				account = cookie.getValue();	//找到账号的Cookie值 
				account = URLDecoder.decode(account,"UTF-8");//解码  ,还原中文字符串的值 
			}
			if(cookie.getName().equals("md5Account")){
				md5Account = cookie.getValue();	//找到加密账号的Cookie值  
			}
		}
	}
	if(account!=null&&md5Account!=null){
		loginFlag = md5Account.equals(MakeMD5.getMD5(account));
	}
 %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>利用Cookie实现永久登录</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">
		.style1{
			width: 400px;
			height: 200px;
			border: 1px solid;
			border-color: green;
		}
		table{
			font-size: 14px;
			color: navy;
			font-family: 楷体;
		}
		input{
			font-size: 14px;
			color: navy;
			font-family: 楷体;
		}
		.btn{
			font-size: 14px;
			background-color:orange;
			color: white;
			font-family: 楷体;
		}
	</style>
  </head>
  
  <body>
  <%
  	if(loginFlag){
   %>
   <fieldset class="style1" >
  	<legend>欢迎您回来</legend>
  		<table align="center">
  			<tr>
  				<td><%=account %>,欢迎您登录本网站!</td>
  				<td align="center">
  					<a href="<%=basePath%>foreverlogin?action=logout">注销登录</a>
  				</td>
  			</tr>
  		</table>
   </fieldset>
   <%}else{ %>
  <fieldset class="style1">
  	<legend>用户登录</legend>
  	
    <form action="foreverlogin?action=login" method="post">
    	<table align="center">
    		<tr>
    			<td>账号:</td>
    			<td><input type="text" name="account"></td>
    		</tr>
    		<tr>
    			<td>密码:</td>
    			<td><input type="password" name="pwd"></td>
    		</tr>
    		<tr>
    			<td>有效期:</td>
    			<td>
    				<input type="radio" name="timeout" value="-1" checked="checked">关闭浏览器即失效<br/>
    				<input type="radio" name="timeout" value="<%=30*24*60*60 %>">30天内有效<br/>
    				<input type="radio" name="timeout" value="<%=Integer.MAX_VALUE %>">永久有效
    			</td>
    		</tr>	
    		<tr>
    			<td colspan="2" align="center"><input type="submit" value="登  录" ></td>
    		</tr>	
    	</table>
    </form>
   </fieldset>
   <%} %>
  </body>
</html>

ForeverLoginServlet类,判断调用用户登录方法或用户注销的方法

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

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



import com.cn.zj.tool.MakeMD5;

public class ForeverLoginServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public ForeverLoginServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");	//设置请求编码格式
		response.setCharacterEncoding("UTF-8");	//设置响应编码格式
		String action = request.getParameter("action");//获得action参数,主要判断是登录还是注销
		if("login".equals(action)){
			this.login(request, response);		//调用login方法
		}else if("logout".equals(action)){
			this.logout(request, response);		//调用logout方法
		}
	}
	/**
	 * 该方法处理用户登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void login(HttpServletRequest request,HttpServletResponse response)
			throws ServletException, IOException{
		String account = request.getParameter("account");	//获得账号
		String pwd = request.getParameter("pwd");			//获得密码
		int timeout= Integer.parseInt(request.getParameter("timeout"));//获得登录保存时间的期限
		String md5Account = MakeMD5.getMD5(account);		//将账号加密
		account = URLEncoder.encode(account,"UTF-8");		//如果账号是中文,需要转换Unicode才能保存在Cookie中
		Cookie accountCookie = new Cookie("account",account);//将账号保存在Cookie中
		accountCookie.setMaxAge(timeout);					//设置账号Cookie的最大保存时间
		Cookie md5AccountCookie = new Cookie("md5Account",md5Account);//将加密后的账号保存在Cookie中
		md5AccountCookie.setMaxAge(timeout);				//设置加密后的账号最大保存时间
		response.addCookie(accountCookie);					//写到客户端的Cookie中
		response.addCookie(md5AccountCookie);				//写到客户端的Cookie中
		try {
			Thread.sleep(1000);								//将此线程暂停1秒后继续执行
		} catch (InterruptedException e) {	
			e.printStackTrace();
		}
		//将页面重定向到用户登录页
		response.sendRedirect("index.jsp?"+System.currentTimeMillis());
	}
	/**
	 * 该方法处理用户注销
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void logout(HttpServletRequest request,HttpServletResponse response)
			throws ServletException, IOException{
		Cookie accountCookie = new Cookie("account","");	//创建一个空的Cookie
		accountCookie.setMaxAge(0);							//设置此Cookie保存时间为0
		Cookie md5AccountCookie = new Cookie("md5Account","");//创建一个空的Cookie
		md5AccountCookie.setMaxAge(0);						//设置此Cookie保存时间为0
		response.addCookie(accountCookie);		//写到客户端Cookie中,将覆盖名为account的Cookie
		response.addCookie(md5AccountCookie);	//写到客户端Cookie中,将覆盖名为md5AccountCookie的Cookie
		try {
			Thread.sleep(1000);					//将此线程暂停1秒后继续执行
		} catch (InterruptedException e) {	
			e.printStackTrace();
		}
		//将页面重定向到用户登录页
		response.sendRedirect("index.jsp?"+System.currentTimeMillis());
	}

	public void init() throws ServletException {
		
	}

}

web.xml文件配置

<servlet>
  	<servlet-name>ForeverLoginServlet</servlet-name>
  	<servlet-class>com.cn.zj.Servlet.ForeverLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ForeverLoginServlet</servlet-name>
  	<url-pattern>/foreverlogin</url-pattern>
  </servlet-mapping>

猜你喜欢

转载自blog.csdn.net/weixin_44234912/article/details/88627428