Cookie学习总结-登陆案例(记住用户名和密码)

本文介绍了一个使用Cookie技术实现用户登录和状态保持的简单Web应用实例。通过创建和读取Cookie,用户可以避免每次访问都需要重新登录的情况,提高了用户体验。详细展示了如何在Servlet中处理GET和POST请求,以及如何在JSP页面中展示登录界面和处理登录操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LoginServlet.java

package blank.servlet;

import java.io.IOException;

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

public class LoginServlet extends HttpServlet {

    // 声明cookie对象
    private Cookie cookieName = null;
    private Cookie cookiePass = null;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建cookie对象
        createCookies(request);
        // 获取oper参数的值
        String oper = request.getParameter("oper");
        // 判断参数值
        if ("pre".equals(oper)) {
                //获取cookie中的值
                String name = cookieName.getValue();
                String pass = cookiePass.getValue();
                //判断是否是初始化的值
                if(!"1".equals(name)){
                    //存储到request域中
                    request.setAttribute("name", name);
                }
                //判断是否是初始化的值
                if(!"1".equals(pass)){
                    //存储到request域中
                    request.setAttribute("pass", pass);
                }

            // 跳转到登陆界面
            request.getRequestDispatcher("/login.jsp").forward(request,
                    response);

        } else if ("login".equals(oper)) {
            // 登陆处理的时候
            //获取用户名
            String name = request.getParameter("name");
            //获取用户的密码
            String pass = request.getParameter("pass");

            if ("leo".equals(name) && "leo".equals(pass)) {
                //修改cookie信息的值
                cookieName.setValue(name);
                cookiePass.setValue(pass);
                // 响应给浏览器的操作
                response.addCookie(cookieName);
                response.addCookie(cookiePass);
                // 跳转到登陆界面
                request.getRequestDispatcher("./index.jsp").forward(request,
                        response);
            } else {
                //重新修改值
                cookieName.setValue(name);
                //删除cookiePass
                cookiePass.setValue("1");//删除
                response.addCookie(cookiePass);//响应给浏览器
                response.addCookie(cookieName);
                // 跳转到登陆界面
                request.getRequestDispatcher("./login.do?oper=pre").forward(request,
                        response);
            }

        }
    }

    /**
     * 创建cookie对象
     * @param request
     */
    private void createCookies(HttpServletRequest request) {
        //获取所有的cookie对象
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (Cookie ck : cookies) {
                //获取cookie的名称
                String name = ck.getName();
                //判断
                if ("name".equals(name)) {
                    cookieName = ck;
                } else if ("pass".equals(name)) {
                    cookiePass = ck;
                }
            }
        }

        //创建要存储用户名的cookie对象
        if (cookieName == null) {
            cookieName = new Cookie("name", "1");
        }
        //创建要存储用户密码的cookie对象
        if (cookiePass == null) {
            cookiePass = new Cookie("pass", "1");
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

login.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 '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>
    <h3>用户登录界面</h3>
    <form action="./login.do?oper=login" method="post">
        用户名:<input type="text" name="name" value="${name}" /><br /> 密码:<input type="password"
            name="pass" value="${pass}" /><br /> <input type="submit" value="登陆" />

       <br/>
    </form>
</body>
</html>

index.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 'index.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>

    <div>
         <a href="./login.do?oper=pre">登陆</a>
    </div>
</body>
</html>

运行效果
1.http://localhost:8080/web_8/index.jsp
这里写图片描述

2.点击登陆
这里写图片描述

3.输入用户名、密码(正确用户名和密码都是leo)
测试输入正确用户名和密码:
这里写图片描述
点击登陆跳转到index.jsp,代表登陆成功。
这里写图片描述
再次点击登陆,可发现浏览器已记住用户名和密码,直接点登陆即可成功登陆
这里写图片描述

测试输入错误用户名或密码:
这里写图片描述
点击登陆–》登陆失败,浏览器已经记住用户名,并未记录错误密码
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值