【Servlet07】Cookie和Seesion

1 Cookie类

API介绍:

Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.

The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method. Several cookies might have the same name but different path attributes.

Cookies affect the caching of the Web pages that use them. HTTP 1.0 does not cache pages that use cookies created with this class. This class does not support the cache control defined with HTTP 1.1.

This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability.

Cookie对象可以将应用程序中的数据以键值对的方式存储在浏览器端的硬盘中,实际应用有购物商城中的购物车功能、登录系统中免登录以及记住账号密码功能等;

1.1 保存Cookie

保存Cookie首先需要一个Cookie对象,由于Cookie是类因此需要要到Cookie的有参构造Cookie(String name, String value),然后再调用相关的方法进行存储,编写html和Servlet进行演示:

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="saveCookie?id=1001&name=华为手机">手机加入购物车</a>
<a href="saveCookie?id=1002&name=华为电脑">电脑加入购物车</a>
</body>
</html>

Servlet:

@WebServlet("/saveCookie")
public class SaveCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        Cookie cookie = new Cookie(id, name);
        cookie.setMaxAge(40);
        response.addCookie(cookie);

        PrintWriter out = response.getWriter();
        out.write("<h3>保存成功</h3>");

    }
}

其中的关键代码:

  • Cookie cookie = new Cookie(id,name);:创建Cookie对象,有参构造的参数就是Cookie要保存的数据,采取键值对的方式;

  • cookie.setMaxAge(40);:设置Cookie数据的有效时间 单位是秒(可选);

  • response.addCookie(cookie);:将Cookie对象加入到响应中,就会将数据保存在浏览器的磁盘中;

添加完毕以后,可以通过浏览器进行查看:

点击展开可以看到详细的信息:

1.2 获取Cookie

存储完毕Cookie以后便是获取Cookie进行应用,更新一下html代码方便做展示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="saveCookie?id=1001&name=华为手机">手机加入购物车</a>
<a href="saveCookie?id=1002&name=华为电脑">电脑加入购物车</a>
<a href="showCookie">展示购物车</a>
</body>
</html>

对应的Servlet:

@WebServlet("/showCookie")
public class ShowCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            out.write(name+":"+value+"<br>");
        }
    }
}

其中的关键方法:

  • Cookie[] cookies = request.getCookies();:从浏览器端的磁盘中获取cookie数据;

  • cookie.getName();cookie.getValue();:获取一系列的cookie信息;

测试结果:

2 HttpSession接口

API介绍:

Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.

This interface allows servlets to

  • View and manipulate information about a session, such as the session identifier, creation time, and last accessed time

  • Bind objects to sessions, allowing user information to persist across multiple user connections

When an application stores an object in or removes an object from a session, the session checks whether the object implements HttpSessionBindingListener. If it does, the servlet notifies the object that it has been bound to or unbound from the session. Notifications are sent after the binding methods complete. For session that are invalidated or expire, notifications are sent after the session has been invalidated or expired.

When container migrates a session between VMs in a distributed container setting, all session attributes implementing the HttpSessionActivationListener interface are notified.

A servlet should be able to handle cases in which the client does not choose to join a session, such as when cookies are intentionally turned off. Until the client joins the session, isNew returns true. If the client chooses not to join the session, getSession will return a different session on each request, and isNew will always return true.

Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.

HttpSession接口来自于 Servlet 规范中的接口,其实现类由 Http 服务器提供,习惯上将 HttpSession 的实现类对象称为会话作用域对象,同一个浏览器只能存在一个Session对象;

2.1 Session对象的创建

Session对象的创建比较特殊,有以下两点规则:

  • 如果访问了一个jsp页面,Session对象则会被自动创建

  • 如果没有访问jsp页面,则需要手动地使用代码去创建Seesion对象;

其中使用代码手动创建对象主要使用到的方法是HttpSession getSession()及其重载HttpSession getSession(boolean create)

使用示例:

@WebServlet("/session")
public class SessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println(session);
        System.out.println(session.isNew());
    }
}
  • session.isNew():返回session对象是否是新创建的

    • 返回true表示是新创建的;

    • 返回false表示是原来创建的;

  • HttpSession getSession()使用规则:

    • 如果内存在已经存在session对象,则直接获取内存中的session对象返回;

    • 如果内存中不存在session对象,服务器会先创建一个新的session对象,然后返回;

  • HttpSession getSession(boolean create)使用规则:

    • request.getSession(true);和无参完全一致

    • request.getSession(false);

      • 如果内存在已经存在session对象,直接获取内存中的session对象返回;

      • 如果内存中不存在session对象,直接返回null

访问JSP后再访问Servlet,查看结果:

不访问JSP,直接访问Servlet,查看结果:

如果将getSession(boolean create)的参数改成false,并且不访问jsp直接去访问Sevlet,则会报空指针异常:

2.2 Session对象的销毁

Session对象的销毁规则如下:

  • Session对象在内存中存在1800秒之后,并且期间如果没有使用Session,则会被自动销毁;另外也可以通过setMaxInactiveInterval方法设置自定义的超时时间;

  • Session对象被创建后,服务器将自动地以cookie的方式将Session对象中SESSIONID值,保存在浏览器的硬盘中;如果在Session的有效时间内,手动地清除了保存SESSIONID的Cookie对象,则此时session也会被销毁;

演示:

Servlet:

@WebServlet("/session")
public class SessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println(session);
        System.out.println(session.isNew());
        System.out.println(session.getMaxInactiveInterval());
        System.out.println(session.getId());
    }
}

查看结果:

可以看到默认的超时时间是1800s,并且输出了Session的id为0A9922E732D30C0C76A444B6305A327F,查看浏览器的Cookie:

可以等待1800s不操作Session对象让Session对象自动销毁,也可以手动删除这条键为JSESSIONID的Cookie来销毁Session对象;

2.3 Session对象的使用

Session对象是一个作用域对象,可以像ServletContext、Request对象那样存储数据,并且用到的方法也相似,不过Session对象存储的作用域数据的使用范围是一次会话

三者的作用范围参考:

Session作用域数据操作的主要方法:

  • java.lang.Object getAttribute(java.lang.String name)方法:通过键获取Session对象中对应的值;

  • void removeAttribute(java.lang.String name)方法:通过键删除Session对象中某个键值对;

  • void setAttribute(java.lang.String name, java.lang.Object object)方法:向某个Session对象中存储一个键值对,如果存在键相同的情况则覆盖之前存储的值;

 

版权声明:
作者:jackqiang
链接:http://www.jackqiang.com/javaweb/server/servlet/2144/cookie_seesion/
来源:JackQiang's
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录