Cookie | Cookie实现oa项目十天内免登陆

news/2024/5/18 16:39:47 标签: 服务器, 前端, cookie

一:Cookie实现十天内免登陆

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

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

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

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

第二步:修改前端页面

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

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

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

<%@page contentType="text/html;charset=UTF-8"%>
<%--表示访问jsp的时候不生成session对象--%>
<%@page session="false" %>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>欢迎使用OA系统</title>
	</head>
	<body>

		<%--<a href="<%=request.getContextPath()%>/dept/list">查看部门列表</a>--%>
		<h1>LOGIN PAGE</h1>
		<hr>
		<form action="<%=request.getContextPath()%>/dept/login" method="post">
			username:<input type="text" name="username"><br>
			password:<input type="password" name="password"><br>
			
			<!--在最初index.jsp的登录页面添加一个复选框-->
			<input type="checkbox" name="flag" value="1">十天内免登录<br>
			
			<input type="submit" value="login">
		</form>

	</body>
</html>

登录时就可以获取到对应的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 {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取servlet path
        String 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);
            // 执行sql
            rs = 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,没有就新创建一个session
            HttpSession session = request.getSession();
            // 把用户名放进session
            session.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(只要访问这个应用,浏览器就一定要携带这两个cookiecookie1.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文件中配置一个局部变量(优先访问的是局部)作为实现上述功能的页面

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <welcome-file-list>
        <welcome-file>welcome</welcome-file>
    </welcome-file-list>
</web-app>

②根据这个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 {
    @Override
    protected 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){
                // 如果登录成功
                // 还是先获取session
                HttpSession 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,实际上是存储到了硬盘里,以后再次访问时就会拿出这个数据与数据库中的用户名和密码进行对比;如果相等就直接进入列表展示页面,如果不等(例如:中途数据库中密码进行更改了或者清除了缓存)就会让你重新进行登录页面!

http://www.niftyadmin.cn/n/16843.html

相关文章

高级路由期末命令配置

文章目录前提要求(1)拓扑图搭建及IP地址规划拓扑图配置&#xff1a;IP地址表规划表1网络连接规划表表2 网络设备明细表表3 IP规划表&#xff08;2&#xff09;OSPF&#xff08;3&#xff09;BGP&#xff08;4&#xff09;路由引入&#xff08;5&#xff09;路由选择&#xff08…

开发c语言日常记录之文件读写以及遍历

1.导包 #include <fcntl.h> #include <stdio.h> #include <unistd.h> 2.文件读取 //根据地址读取内容 绝对地址 比如/sdcard/a.txt void FileReadString(char *path,char *buf) {int fd open(path, O_RDONLY);if (fd -1) {printf("can not open the …

Kafka极客 - 15 重设消费者位移 Offset

文章目录1. 为什么要重设消费者组位移&#xff1f;2. 重设位移策略3. 消费者 API 方式设置4. 命令行方式设置1. 为什么要重设消费者组位移&#xff1f; 我们知道&#xff0c;Kafka 和传统的消息引擎在设计上是有很大区别的&#xff0c;其中一个比较显著的区别就是&#xff0c;…

Elastic Job 分布式任务调度

1. Elastic Job1.1前言 我们开发定时任务一般都是使用quartz或者spring-task&#xff0c;无论是使用quartz还是spring-task&#xff0c;我们至少会遇到以下两个痛点&#xff1a; l 不敢轻易跟着应用服务器多节点部署&#xff0c;可能会重复多次执行而引发系统逻辑的错误。 l qu…

Python——列表的常用操作

1.append&#xff1a; cities [北京] cities.append(上海) 2.count&#xff1a;统计某个元素在泪飙中出现的次数 temps [to,be,or,not,to,be] print(temps.count(to)) 3.extend&#xff1a;将一个列表中元素追加到另外一个列表中 a [1,2,3] b [4,5,6] c a.extend(b) 4.ins…

基于springboot高校闲置物品交易系统微信小程序源码和论文

基于springboot二手物品交易系统微信小程序 互联网的兴起从本质上改变了整个社会的商品交易方式&#xff0c;国内各大企业从上个世纪 90 年代互联网兴起之时&#xff0c;就产生了通过网络进行销售经营商品的想法。但是由于在互网上企业的信誉难以认证、网络的法规政策不健全、物…

【华为机试真题 Python实现】2022年4季度最新机试题

文章目录2022年4季度最新机试题机试必须要会的函数输入输出处理for 循环通过下标访问元素直接迭代访问元素同时访问下标和元素while 循环字符ASSIC码转换进制转换绝对值计算幂运算最值选取排序2022年4季度最新机试题 最近准备华为OD社招的同学还比较多&#xff0c;已经有1k多的…

山东省知识产权贯标奖励政策汇总

济南 济南市对当年通过国家知识产权管理规范标准认证的企事业单位给予最高2万元/家资助。 历城区 对当年新通过国家知识产权管理规范标准认证的企事业单位给予最高10万元奖励。 市中区 对新认定或新引进的专利贯标企业&#xff0c;一次性最高给予5万元扶持资金。 槐荫区 …