吴裕雄--天生自然JAVA开发JSP-Servlet学习笔记:response对象-增加Cookie

<%-- 
    Document   : addCookie
    Created on : 2020-4-12, 8:16:06
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> 增加Cookie </title>
    </head>
    <body>
        <%
// 获取请求参数
            String name = request.getParameter("name");
// 以获取到的请求参数为值,创建一个Cookie对象
            Cookie c = new Cookie("username", name);
// 设置Cookie对象的生存期限
            c.setMaxAge(24 * 3600);
// 向客户端增加Cookie对象
            response.addCookie(c);
        %>
    </body>
</html>

<%-- 
    Document   : readCookie
    Created on : 2020-4-12, 8:23:18
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> 读取Cookie </title>
    </head>
    <body>
        <%
// 获取本站在客户端上保留的所有Cookie
            Cookie[] cookies = request.getCookies();
// 遍历客户端上的每个Cookie
            for (Cookie c : cookies) {
                // 如果Cookie的名为username,表明该Cookie是需要访问的Cookie
                if (c.getName().equals("username")) {
                    out.println(c.getValue());
                }
            }
        %>
    </body>
</html>

原文地址:https://www.cnblogs.com/tszr/p/12683637.html