Cookie和Session

1.Cookie

a)什么是cookie

  1. Cookie是服务器通知客户端保存键值对的一种技术
  2. 客户端有了Cookie后,每次请求都发送给服务器
  3. 每个Cookie的大小不能超过4kb

b)如何创建Cookie

public class CookieServlet extends BaseServlet{
    protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 创建Cookie对象
        Cookie cookie = new Cookie("key1","value1");
        //2 通知客户端保存Cookie
        resp.addCookie(cookie);

        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("Cookie创建成功");
    }
}

 c)服务器如何获取Cookie

        服务器获取客户端代码中只需一行代码

    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        Cookie iwant = null;
        for (Cookie c:
             cookies) {
            resp.getWriter().write("Cookie["+c.getName()+"="+c.getValue()+"]\n");

        }
        iwant = CookieUtils.findCookie("key1",cookies);

        if (iwant != null){
            resp.getWriter().write("find the cookie that needs");
        }
    }

public class CookieUtils {
    public static Cookie findCookie(String name,Cookie[] cookies){
        if(name == null || cookies == null || cookies.length == 0){
            return null;
        }
        for (Cookie c: cookies) {
            //获取特有Cookie
            if(name.equals(c.getName())){
                return c;
            }
        }

        return null;
    }
}

 d)Cookie值的修改

方案一:

  1. 先创建一个要修改的同名的Cookie对象
  2. 在构造器,同时赋予新的Cookie值
  3. 调用response.addCookie(Cookie);
    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Cookie cookie = new Cookie("key1","newValue1");
        resp.addCookie(cookie);
        resp.getWriter().write("Cookie值已完成修改");

    }

方案二:

  1. 先查找需要修改的Cookie对象
  2. 调用setValue方法赋予新的Cookie值
  3. 调用response.addCookie()通知客户端保存修改
    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Cookie key2 = CookieUtils.findCookie("key2", req.getCookies());

        if (key2 != null){
            key2.setValue("newValue2");
            resp.addCookie(key2);
            resp.getWriter().write("Cookie值已完成修改");
        }
        
    }

f)Cookie的生命控制

        Cookie的生命控制指的是如何管理Cookie什么时候被销毁(删除)

        setMaxAge() 设置Cookie的最大生存空间,正数表示指定的秒数后过期,负数(默认-1)表示浏览器关闭后Cookie被删除,0表示马上删除Cookie

    //默认生命周期为浏览器关闭时销毁
    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("defaultLife", "defaultLife");
        cookie.setMaxAge(-1);//设置存活时间
        resp.addCookie(cookie);
    }
    //立即销毁
    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie defaultValue = CookieUtils.findCookie("defaultLife", req.getCookies());
        if(defaultValue != null){
            defaultValue.setMaxAge(0);  //立刻删除
            resp.addCookie(defaultValue);
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().write("defaultLife的Cookie已经被删除");
        }
    }
    //生存一个小时
    protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("life3600", "life3600");
        cookie.setMaxAge(3600);
        resp.addCookie(cookie);
    }

g)Cookie有效路径Path的设置

        Cookie的path属性可以有效的过滤哪些Cookie可以发送服务器,哪些不发。

        path属性是通过请求的地址来进行有效的过滤。

        CookieA                Path=/工程路径

        CookieB                Path=/工程路径/abc

请求地址:

        http://ip:port/工程路径/a.html:CookieA发送,CookieB不发送

        http://ip:port/工程路径/abc/a.html:CookieA发送,CookieB发送

    protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("Path1", "path1");
        //getContextPath()得到工程路径
        cookie.setPath(req.getContextPath()+"/abc");  //      ====> /工程路径/abc
        resp.addCookie(cookie);
    }

 h)Cookie练习---免输入用户名登录

              

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("lili".equals(username) && "123456".equals(password)){
            Cookie username1 = new Cookie("username", username);
            username1.setMaxAge(60*60*24*7);
            resp.addCookie(username1);
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }
    }
}

<body>
    <form action="http://localhost:8080/CookieAndSession/lg" method="get">
        用户名:<input type="text" name="username" value="${cookie.username.value}"> <br>
        密码:<input type="text" name="password"> <br>
        <input type="submit" value="登录">
    </form>
</body>

2.Session

a)什么是Session

1.Session就是一个接口(HttpSession)。

2.Session就是会话。用来维护客户端和服务器之间关联的一种技术。

3.每个客户端都有自己的一个Session会话。

4.Session会话中,我们经常用来保存用户登陆之后的信息。

b)如何创建Session和获取(id号,是否为新)

Request.getSession():

        第一次调用是创建Session

        之后调用是获取前面创建好的Session对象

isNew():判断是不是刚创建出来的(新的)

        true 表示刚创建

        false 表示获取之前创建

每个会话都有一个身份号码(ID值),且唯一,通过getId()得到Session的id值

    protected void createSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建或获取Session
        HttpSession session = req.getSession();
        //判断是否是新创建的
        boolean aNew = session.isNew();
        //获取Session的唯一id
        String id = session.getId();

        resp.setContentType("text/html;charset=UTF-8");

        resp.getWriter().write("得到的Session的id是"+id+"<br>");
        resp.getWriter().write("这个Session是否是新创建的"+aNew);
    }

c)Session域数据的存取

    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("key1","value1");
    }

    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object key1 = req.getSession().getAttribute("key1");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("从Session中获取的数据为"+key1);
    }
    

d)Session生命周期控制

    setMaxInactiveInterval()设置Session的超时时长(以秒为单位)和getMaxInactiveInterval()获取Session的超时时长。正数是设定Session超时时长,负数是永不超时
    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("默认时长为"+maxInactiveInterval+"s"); //1800s
    }

在Tomcat的web.xml文件中:

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

可以在项目的web.xml文件中进行修改项目Session的默认时长

 e)浏览器和Session之间关联的技术内幕

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值