javaWeb学习笔记9—Cookie,Session

学习视频地址Java Web 尚硅谷

Cookie

cookie 保存在客户端

image-20220303193837252

1.创建cookie

image-20220303204522432

protected void creatCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Cookie cookie = new Cookie("key1", "value1");
    resp.addCookie(cookie);

    resp.getWriter().write("cookie创建成功");
}

image-20220303210015344

2.服务器获取cookie

image-20220303213432229

   protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Cookie[] cookies = req.getCookies();
        Cookie iwantcookie =null;
        for (Cookie cookie : cookies) {
          //  resp.getWriter().write(cookie.getName()+"="+cookie.getValue()+"<br/>");
            if (cookie.getName().equals("key1")){
                iwantcookie=cookie;
            }
        }
        if (iwantcookie != null){
            resp.getWriter().write(iwantcookie.getValue());
        }
    }

通常写一个工具类:

public class CookieUtils {
    public static Cookie findCookie(String name, Cookie[] cookies) {
        if (name == null || cookies.length == 0 || cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie;
            }
        }
        return null;
    }
}
3.修改Cookie的值

方法一:(不常用)

相当于覆盖了

image-20220304092510070

方法二:

image-20220304092644959

4.Cookie生命周期控制

image-20220304094332714

cookie.setMaxAge的默认值是-1 , 在控制台显示为Session

image-20220304100527911

key1.setMaxAge(0);马上删除, 响应里的细节

image-20220304101159118

这里生命截止时间 是格林时间(格林威治标准时间,GMT), 东八区[GMT+8]

image-20220304103011501

5.Cookie的path属性

有效过滤cookie,路径满足条件 resp才会发送cookie

image-20220304104759663

默认值是当前路径

image-20220304105241790

以上的测试代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie</title>
<style type="text/css">

   ul li {
      list-style: none;
   }
   
</style>
</head>
<body>
   <iframe name="target" width="500" height="500" style="float: left;"></iframe>
   <div style="float: left;">
      <ul>
         <li><a href="cookieServlet?action=creatCookie" target="target">Cookie的创建</a></li>
         <li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>
         <li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li>
         <li>Cookie的存活周期</li>
         <li>
            <ul>
               <li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)</a></li>
               <li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li>
               <li><a href="cookieServlet?action=lift3600" target="target">Cookie存活3600秒(1小时)</a></li>
            </ul>
         </li>
         <li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li>
         <li><a href="" target="target">Cookie的用户免登录练习</a></li>
      </ul>
   </div>
</body>
</html>
@WebServlet(name = "CookieServlet", value = "/cookieServlet")
public class CookieServlet extends BaseServlet{
    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Cookie[] cookies = req.getCookies();
        Cookie iwantcookie =null;
        for (Cookie cookie : cookies) {
          //  resp.getWriter().write(cookie.getName()+"="+cookie.getValue()+"<br/>");
            if (cookie.getName().equals("key1")){
                iwantcookie=cookie;
            }
        }
        if (iwantcookie != null){
            resp.getWriter().write(iwantcookie.getValue());
        }
    }
    protected void creatCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("key1", "value1");
        resp.addCookie(cookie);

        resp.getWriter().write("cookie创建成功");
    }
    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie key1 = CookieUtils.findCookie("key1", req.getCookies());
        key1.setValue("newValue1");
        //通知客户端保存
        resp.addCookie(key1);
    }
    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("keyLife", "ValueLift");
        cookie.setMaxAge(-1);//cookie 的默认值就是这个,表示浏览器一关cookie就会被删除
        resp.addCookie(cookie);
    }
    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie key1 = CookieUtils.findCookie("key1", req.getCookies());
        key1.setMaxAge(0); //马上删除
        resp.addCookie(key1);
        resp.getWriter().write("key1已经删除");
    }

    protected void lift3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("lift3600", "lift3600");
        cookie.setMaxAge(60*60);//一个小时后删除
        resp.addCookie(cookie);
        resp.getWriter().write("创建了一个存活时间是1小时的cookie");
    }

    protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("testPath", "testPath");
        //getContextPath 获取工程路径
        cookie.setPath(req.getContextPath()+"/abc");
        resp.addCookie(cookie);
        resp.getWriter().write("创建了一个有路径的cookie");
    }
}
{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {



        String action = req.getParameter("action");
        try {
            req.setCharacterEncoding("utf-8");
            //解决中文乱码问题
            resp.setContentType("text/html; charset=utf-8");
            // 获取action业务鉴别字符串,获取相应的业务 方法反射对象
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            //System.out.println(method);
            // 调用目标业务 方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
6.练习——免用户名登入

image-20220304191714515

package com.example.cookie_session.servlet;

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(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if ("admin".equals(username) && "123456".equals(password)) {
            //登录 成功
            Cookie cookie = new Cookie("username", username);
            cookie.setMaxAge(60 * 60 * 24 * 7);//当前Cookie一周内有效
            resp.addCookie(cookie);
            System.out.println("登录 成功11");
        } else {
//            登录 失败
            System.out.println("登录 失败");
        }

    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:8080/cookie_session/loginServlet" method="get">
        用户名:<input type="text" name="username" value="${cookie.username.value}"> <br>
        密码:<input type="password" name="password"> <br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

Session

cookie 保存在客户端 session保存在服务器

image-20220304170154969

1.获取和创建

image-20220304170838475

2.session域数据存取
3.session生命周期控制

session的默认生命周期在tomcat的web.xml 文件中配置过了。一般是30分钟。

image-20220304181039348

image-20220304181123583

image-20220304181208774

修改单独session:

// 先获取Session对象
HttpSession session = req.getSession();
// 设置当前Session3秒后超时
session.setMaxInactiveInterval(3);

image-20220304181839998

image-20220304181940337

相当于 cookie的0,马上删除。

  • 一直点,一直创建新的Session

image-20220304181746804

public class SessionServlet extends BaseServlet {
    /**
     * 往Session中保存数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("key1", "value1");
        resp.getWriter().write("已经往Session中保存了数据");

    }

    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取了Session的默认超时时长
        int maxInactiveInterval = req.getSession().getMaxInactiveInterval();

        resp.getWriter().write("Session的默认超时时长为:" + maxInactiveInterval + " 秒 ");

    }

    protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取Session对象
        HttpSession session = req.getSession();
        // 设置当前Session3秒后超时
        session.setMaxInactiveInterval(3);

        resp.getWriter().write("当前Session已经设置为3秒后超时");
    }

    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取Session对象
        HttpSession session = req.getSession();
        // 让Session会话马上超时
        session.invalidate();

        resp.getWriter().write("Session已经设置为超时(无效)");
    }

    /**
     * 获取Session域中的数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object attribute = req.getSession().getAttribute("key1");
        resp.getWriter().write("从Session中获取出key1的数据是:" + attribute);
    }



    protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建和获取Session会话对象
        HttpSession session = req.getSession();
        // 判断 当前Session会话,是否是新创建出来的
        boolean isNew = session.isNew();
        // 获取Session会话的唯一标识 id
        String id = session.getId();

        resp.getWriter().write("得到的Session,它的id是:" + id + " <br /> ");
        resp.getWriter().write("这个Session是否是新创建的:" + isNew + " <br /> ");
    }
}
4.浏览器和Session之间关联的技术

Session技术,底层其实是基于Cookie技术来实现的。

image-20220304192649228

所以浏览器关闭后这个session就找不到了,因为这个session对应的cookie已经删除,cookie默认在浏览器关闭后删除。

image-20220304214853919

Tomcat内存中还有上次session 的id对应的session内容 但是新的的请求本身没有id值(cookie中JSESSION),所以Tomcat重新创建 所有session要有超时时间。

cookie用来自动登录,session用来保持登录状态

因为http是无状态的,没法保存信息,但每次浏览器请求数据时,可能需要携带大量重复信息

所以就需要cookie和session来存储这些信息【比如登陆的用户信息等】

其中cookie是客户端用于记录,session用于服务端记录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值