Cookie | Cookie实现oa项目十天内免登陆
创始人
2024-04-23 02:00:33
0

一:Cookie实现十天内免登陆

第一步:要先先实现登录功能

这个在前面的博客中已经实现了:

        ①登录成功:跳转到部门列表页面

        ②登录失败:跳转到登录失败页面

第二步:修改前端页面

在登录页面给一个复选框(checkbox),复选框后面给一句话:十天内免登录。

        ①用户选择了复选框:表示要支持十天内免登录。

        ②用户没有选择复选框:表示用户不想使用十天内免登录功能。

<%@page contentType="text/html;charset=UTF-8"%>
<%--表示访问jsp的时候不生成session对象--%>
<%@page session="false" %>

欢迎使用OA系统<%--/dept/list">查看部门列表--%>

LOGIN PAGE


/dept/login" method="post">username:
password:
十天内免登录

登录时就可以获取到对应的name和value

第三步:修改Servlet中的login方法

①登录成功,在跳转到列表页面之前,调用request对象的getParameter(“flag”)方法,看有没有选择十天免登录;如果选择了:需要先创建Cookie对象,把登录名username 和 密码password 都放进去;并且调用Cookie对象的setMaxAge方法设置其有效期为十天。

②调用Cookie对象的setPath方法,设置Cookie的path为当前项目名;只要访问这个应用,浏览器就一定要携带登录名username 和 密码password的Cookie对象。

③调用response的addCookie方法,响应Cookie到浏览器

package com.bjpowernode.oa.web.action;import com.bjpowernode.oa.utils.DBUtil;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*** @Author:朗朗乾坤* @Package:com.bjpowernode.oa.web.action* @Project:JavaWeb* @name:UserServlet* @Date:2022/11/28 19:59*/
@WebServlet({"/dept/login","/dept/exit"})
public class UserServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取servlet pathString servletPath = request.getServletPath();if("/dept/login".equals(servletPath)){doLogin(request,response);}else if("/dept/exit".equals(servletPath)){doExit(request,response);}}/*** 退出系统,手动销毁session对象* @param request* @param response* @throws ServletException* @throws IOException*/protected void doExit(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取当前session对象HttpSession session = request.getSession(false);// 销毁session对象if (session != null) {// 手动销毁session.invalidate();// 销毁以后,跳到登录页面response.sendRedirect(request.getContextPath()+"/index.jsp");}}/*** 登录,创建session对象* @param request* @param response* @throws ServletException* @throws IOException*/protected void doLogin(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 打一个布尔标记boolean success = false;// 获取前端提交的用户名和密码String username = request.getParameter("username");String password = request.getParameter("password");// 连接数据库进行验证Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {// 获取连接conn = DBUtil.getCoonetion();// 获取预编译的数据库操作对象String sql = "select * from t_user where username=? and password=?";ps = conn.prepareStatement(sql);ps.setString(1, username);ps.setString(2, password);// 执行sqlrs = ps.executeQuery();// 如果里面有数据表示登录成功:1条或者0条if (rs.next()) {success = true;}} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(conn, ps, rs);}// 登录成功/失败if (success) {// 登录成功,是一定要获取session// 获取session对象(不需要加参数false,不能返回null)// 必须获取到session,没有就新创建一个sessionHttpSession session = request.getSession();// 把用户名放进sessionsession.setAttribute("username",username);// 登录成功了,并且用户确实选择了“十天内免登录”功能。String flag = request.getParameter("flag");if ("1".equals(flag)) {// 创建Cookie对象存储登录名Cookie cookie1 = new Cookie("username", username);// 创建Cookie对象存储密码Cookie cookie2 = new Cookie("password", password);// 设置cookie的有效期为十天cookie1.setMaxAge(60 * 60 * 24 * 10);cookie2.setMaxAge(60 * 60 * 24 * 10);// 设置cookie的path(只要访问这个应用,浏览器就一定要携带这两个cookie)cookie1.setPath(request.getContextPath());cookie2.setPath(request.getContextPath());// 响应cookie给浏览器response.addCookie(cookie1);response.addCookie(cookie2);}response.sendRedirect(request.getContextPath()+"/dept/list");}else{// 登录失败response.sendRedirect(request.getContextPath()+"/error.jsp");}}
}

第四步:用户再次访问该网站的首页index.jsp的时候,有两个走向

(1)要么直接跳转到部门列表页面;不需要重新登录了!

(2)要么跳转到登录页面;可能修改了密码,需要重新登录!

①注意:原来我们使用的是全局的欢迎页面,默认访问的是登录页面index.jsp;现在要重新在web.xml文件中配置一个局部变量(优先访问的是局部)作为实现上述功能的页面


welcome

②根据这个welcome路径,编写WelcomeServlet类来实现免登陆的功能

package com.bjpowernode.oa.web.action;import com.bjpowernode.oa.utils.DBUtil;import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*** @Author:朗朗乾坤* @Package:com.bjpowernode.oa.web.action* @Project:JavaWeb* @name:WelcomeServlet* @Date:2022/11/30 20:29*/
public class WelcomeServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取cookie// 这个Cookie[]数组可能是null,如果不是null,数组的长度一定是大于0的。Cookie[] cookies = request.getCookies();String username = null;String password = null;if (cookies != null) {// 遍历cookie取出值for (Cookie cookie : cookies) {String name = cookie.getName();if ("username".equals(name)){ // 如果是username// 获取用户名username = cookie.getValue();}else if ("password".equals(name)) {// 如果是password// 获取密码password = cookie.getValue();}}}// 要么都获取不到,要么都获取到if (username != null && password != null) {// 连接数据库,验证用户名和密码是否正确Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;boolean success = false; // 打一个布尔标记try {conn = DBUtil.getCoonetion();String sql = "select * from t_user where username = ? and password = ?";ps = conn.prepareStatement(sql);ps.setString(1,username);ps.setString(2,password);rs = ps.executeQuery();if (rs.next()) {// 登录成功success = true;}} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(conn, ps, rs);}if (success){// 如果登录成功// 还是先获取sessionHttpSession session = request.getSession();session.setAttribute("username", username);// 正确,表示登录成功,直接跳转到列表页面response.sendRedirect(request.getContextPath() + "/dept/list");}else{// 错误,表示登录失败,直接跳转到登录页面(一般是密码更改的原因)response.sendRedirect(request.getContextPath() + "/index.jsp");}}else{// 跳转到登录页面,用户名和密码都没有获取到response.sendRedirect(request.getContextPath() + "/index.jsp");}}
}

总结 

实际上主要就是逻辑思维,我们把登录的用户名和密码放到Cookie里面,并设置了有效期十天>0,实际上是存储到了硬盘里,以后再次访问时就会拿出这个数据与数据库中的用户名和密码进行对比;如果相等就直接进入列表展示页面,如果不等(例如:中途数据库中密码进行更改了或者清除了缓存)就会让你重新进行登录页面!

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...