在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();    //获取请求中所有的Cookieif(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",""); //创建一个空的CookieaccountCookie.setMaxAge(0);                           //设置此Cookie保存时间为0Cookie md5AccountCookie = new Cookie("md5Account","");//创建一个空的Cookiemd5AccountCookie.setMaxAge(0);                        //设置此Cookie保存时间为0response.addCookie(accountCookie);     //写到客户端Cookie中,将覆盖名为account的Cookieresponse.addCookie(md5AccountCookie);  //写到客户端Cookie中,将覆盖名为md5AccountCookie的Cookietry {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>

利用Servlet实现用户永久登录相关推荐

  1. c# MVC利用AuthorizeAttribute验证用户是否登录

    现在多数网站必须验证用户登陆并利用Session或者Cookie存储用户登陆后才能进行操作, 如果存储过期或者没用登陆则自动返回到登陆界面,而MVC自带AuthorizeAttribute属性进行验证 ...

  2. Web---Cookie技术(显示用户上次登录的时间、显示用户最近浏览的若干个图片(按比例缩放))

    本章博客讲解: 1.Cookie基本用法演示 2.演示Cookie的访问权限 3.演示Cookie的删除 4.利用Cookie显示用户上次登录的时间 5.利用Cookie技术显示用户最近浏览的若干个图 ...

  3. 在ASP.NET 中实现单用户登录(利用Cache, 将用户信息保存在服务器缓存中)[转]

    Technorati 标签: asp.net,cache 由于某些原因,在我们的应用中会遇到一个用户只能在一个地方登录的情况,也就是我们通常所说的单点登录.在ASP.NET中实现单点登录其实很简单,下 ...

  4. php登录后自动退出登录,PHP利用Cookie设置用户30分钟未操作自动退出功能

    登陆控制器需要做的登陆成功把用户ID等信息存入cookie: $this->systemSetKey(array('name'=>$admin_info['admin_name'], 'i ...

  5. Servlet+jsp用户登录加上验证码

    最近公司有个项目被客户拿去进行漏洞扫描,发现用户登录太简单,容易被暴力破解.当然发现的问题很多,什么反射型XSS,存储型XSS,敏感信息泄露等等.但是我们今天不讲这么多,就说说如何修复暴力破解的问题. ...

  6. php通过session保存用户信息,如何在php中利用session与cookie保存用户的登录信息

    如何在php中利用session与cookie保存用户的登录信息 发布时间:2020-12-18 15:49:56 来源:亿速云 阅读:95 作者:Leah 如何在php中利用session与cook ...

  7. 利用session完成用户登录

    首先提出一个问题:为什么用session容器来保存用户的登录状态? 因为在一个会话里访问的一些web资源都需要知道用户是否已经登录,所以只能保存在session中,不能是在request中. 首页: ...

  8. 基于 JSP + Servlet 的用户登录验证

    综合案例--基于 JSP + Servlet 的用户登录验证 [例6-1] 实现一个简单的用户登录验证程序,如果用户名是 abc ,密码是 123,则显示欢迎用户的信息,否则显示"用户名或密 ...

  9. java 自动登录功能_jsp实现用户自动登录功能

    理解并掌握cookie的作用以及利用cookie实现用户的自动登录功能,实现下图效果 当服务器判断出该用户是首次登录的时候,会自动跳转到登录界面等待用户登录,并填入相关信息.通过设置cookie的有效 ...

最新文章

  1. apache性能测试工具ab使用详解
  2. nginx 开发一个简单的 HTTP 模块
  3. mysql源 如何编译安装,MySQL5.7.22-源代码编译安装
  4. Unity3D笔记 愤怒的小鸟六 弹弓发射小鸟
  5. 系统相机裁剪比例_拍不出好照片,你缺的不是好手机而是相机设置的秘笈
  6. ie系列浏览器_IE浏览器换Logo,真担心你上网找不到图标
  7. python binascii模块详解
  8. 0706 - 个人品牌建立
  9. 计算机导论的论文范例,★计算机导论论文提纲范文计算机导论论文提纲格式模板...
  10. java gd库_[转]gd库的安装
  11. Java 相关知识的学习(第一章至第三章)
  12. JAVA 命令执行 学习笔记
  13. MySQL开发者需要了解的12个技巧与窍门
  14. 四川大学计算机考研信息汇总
  15. 升级OSX High Sierra 10.13遇到一些问题及解决方法
  16. Mac技巧:新手必看Macbook快捷键使用大全
  17. em表示什么长度单位_html 常见的长度单位”px em pt” 简介说
  18. Origin数据分析功能
  19. ABP VNext学习日记1
  20. 实验3-5 查询水果价格

热门文章

  1. TF学习——TF数据读取:TensorFlow中数据读这三张图片的5个epoch +把读取的结果重新存到read 文件夹中
  2. requirements.txt
  3. java,UDP协议简单实现
  4. linux系统vsftpd登陆慢卡怎么办
  5. Android 程序适应多种多分辨率
  6. 3157 Java vs C++模拟
  7. C语言的函数调用过程(栈帧的创建与销毁)
  8. 关于STM32使用RTC时复位后程序死在 RTC
  9. qt 编译mysql wince_Qt4.8.6开发WinCE 5.0环境搭建
  10. 王勇DRP项目浏览器无法正常显示问题