要么改变世界,要么适应世界

Java Web 通过操控Cookie实现记住密码

2020-09-25 20:24:13
0
目录

什么是Cookie?

引用百度百科的说法,

Cookie,有时也用其复数形式 Cookies。类型为“小型文本文件”,是某些网站为了辨别用户身份,进行Session跟踪而储存在用户本地终端上的数据(通常经过加密),由用户客户端计算机暂时或永久保存的信息

说白了就是将浏览器上面的一些信息保存在用户的电脑上面,当然了这些数据一般不会产生严重影响,因为它永远不会以任何方式执行,也就避免带来了病毒或者攻击用户电脑,并且一般浏览器都会对Cookie的个数有限制,不用担心塞满用户电脑。

有什么用?

可以用来记录用户访问该网站的频率、时间段等,最常用的就是“记住用户名和密码”,在一些登陆网站,当用户登陆的时候选择了“记住密码”,Web服务端就将用户名和密码进行处理(一般就是将密码进行加密),然后将处理后的字符串封装成一个Cookie进行保存。

怎么用?

Java Web为例:

首先新建登陆页面:

<%--
    Author: Yalexin
    Email: 181303209@yzu.edu.cn 
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>


    <%
        String username = "", password = "";
        Cookie[] cookies1 = request.getCookies();
        if (cookies1 != null){
            for (Cookie cookie : cookies1){
                if (cookie.getName().equals("userCookie")){
                    String[] split = cookie.getValue().split("->");
                    username = split[0];
                    password = split[1];
                }
            }
        }
    %>


</head>
<body>


<form action="login_1" method="post">
    <input type="text" name="username" value="<%=username%>">
    <input type="password" name="password" value="<%=password%>">
    <input type="submit" value="登陆">
</form>
</body>
</html>

创建Servlet,处理post请求:

/**
 * Author: Yalexin
 * Email: 181303209@yzu.edu.cn
 **/
package com.yalexin;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/login_1", name = "Login_1Servlet")
public class Login_1Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();
        saveCookie(resp, "userCookie", username + "->" + password, 60 * 60);
        this.getServletContext().setAttribute("username", username);
        resp.sendRedirect("index_1.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    private void saveCookie(HttpServletResponse response, String cookieName, String value, int time) {
        Cookie cookie = new Cookie(cookieName, value);】
        // 以秒为单位
        cookie.setMaxAge(time);
        response.addCookie(cookie);
    }

}

创建登陆成功后的页面:

<%--
    Author: Yalexin
    Email: 181303209@yzu.edu.cn 
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
hello ${username}
<a href="logout_1"> 注销 </a>
</body>
</html>

创建注销Servlet

/**
 * Author: Yalexin
 * Email: 181303209@yzu.edu.cn
 **/
package com.yalexin;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/logout_1", name = "Logout_1Servlet")
public class Logout_1Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        deleteCookieByName(resp, req, "userCookie");
        resp.sendRedirect("login_1.jsp");
    }

    /**
     * 由于没有提供delete方法,可借助 cookie.setMaxAge(0) 将cookie的时间设置成0,即过期状态,间接达到删除目的
     *
     * @param response
     * @param request
     * @param cookieName
     */
    private void deleteCookieByName(HttpServletResponse response, HttpServletRequest request, String cookieName) {
        Cookie cookie = new Cookie(cookieName, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

}
历史评论
开始评论