1. 什么是 Session 会话?


        1、 Session 就一个接口(HttpSession)。


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


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


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



2. 创建 Session 和获取(id 号,是否为新)


        request.getSession()

                第一次调用是:创建 Session 会话

                之后调用都是:获取前面创建好的 Session 会话对象。

                 创建和获取 Session 的 API 是一样的


        isNew(); 判断到底是不是刚创建出来的(新的)

                true 表示刚创建

                false 表示获取之前创建


        每个会话都有一个身份证号。也就是 ID 值。而且这个 ID 是唯一的。

                getId() 得到 Session 的会话 id 值。




代码示例:


html:


<!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>Session</title>
    <base href="http://localhost:8080/14_session/"/>
    <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="sessionServlet?action=createSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li>
        <li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a></li>
        <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li>
        <li>Session的存活</li>
        <li>
            <ul>
                <li><a href="" target="target">Session的默认超时及配置</a></li>
                <li><a href="" target="target">Session3秒超时销毁</a></li>
                <li><a href="" target="target">Session马上销毁</a></li>
            </ul>
        </li>
        <li><a href="" target="target">浏览器和Session绑定的原理</a></li>
    </ul>
</div>
</body>
</html>

BaseServlet:

public abstract class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 解决post请求中文乱码问题
        // 一定要在获取请求参数之前调用才有效
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");
        // 获取 action 业务鉴别字符串,获取相应的业务 方法反射对象
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            // 调用目标业务 方法
            method.invoke(this, request, response);
        } catch (Exception e) {
            // e.printStackTrace();
        }
    }
}

SessionServlet程序:

@WebServlet(name = "SessionServlet", value = "/sessionServlet")
public class SessionServlet extends BaseServlet {
    /**
     * 创建Session对象,并查看其是否为第一次创建及其id值
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void createSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取 Session 对象
        HttpSession session = request.getSession();

        // 2. 查看创建的 Session 对象是否为新
        boolean aNew = session.isNew();

        // 3.查看创建的 Session 对象的ID值
        String id = session.getId();

        response.getWriter().write("已创建了 Session 对象<br />");
        response.getWriter().write("查看创建的 Session 对象是否为新:" + aNew + "<br />");
        response.getWriter().write("查看创建的 Session 对象的ID值:" + id + "<br />");
    }

    /**
     * 往Session中保存数据
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取 Session 对象
        HttpSession session = request.getSession();
        // 2.向 Session 中保存数据
        session.setAttribute("key", "value");

        response.getWriter().write("已经往 Session 中保存了数据<br />");

    }

    /**
     * 获取Session中的数据
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取 Session 对象
        HttpSession session = request.getSession();
        // 2. 获取 Session 域中的数据
        Object key = session.getAttribute("key");

        response.getWriter().write("获取 Session 中的数据为:" + key + "<br />");

    }


}

3. Session 生命周期控制

public void setMaxInactiveInterval(int interval)

        设置 Session 的超时时间(以秒为单位),超过指定的时长,Session就会被销毁。

                值为正数的时候,设定 Session 的超时时长。

                值为负数表示永不超时(极少使用)


public int getMaxInactiveInterval()

        获取 Session 的超时时间


public void invalidate()

        让当前 Session 会话马上超时无效。

3.1 设置并获取默认超时时长的Session对象



        Session 默认的超时时间长为 30 分钟。



        因为在 Tomcat 服务器的配置文件 web.xml中默认有以下的配置,它就表示配置了当前                 Tomcat 服务器下所有的 Session超时配置默认时长为:30 分钟。

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

代码示例:

protected void defaultLift(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取默认超时时长 Session 对象
        HttpSession session = request.getSession();
        // 2. Session 对象的超时时长
        int maxInactiveInterval = session.getMaxInactiveInterval();

        response.getWriter().write("获取 Session 中的默认超时时长为:" + maxInactiveInterval + "<br />");

    }

结果:

java session下线 java中session是什么意思_服务器



        如果说。你希望你的 web 工程,默认的 Session 的超时时长为其他时长。你可以在你自己的 web.xml 配置文件中做以上相同的配置。就可以修改你的 web 工程所有 Seession 的默认超时时长。



示例:



<!--表示当前 web 工程。创建出来 的所有 Session 默认是 20 分钟 超时时长-->
    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>

再次运行Servlet程序,得到结果:

java session下线 java中session是什么意思_前端_02



3.2 设置并获取默认超时时长为3秒的Session对象



        如果你想只修改个别 Session 的超时时长。就可以使用上面的 API。setMaxInactiveInterval(int interval)来进行单独的设置。




        session.setMaxInactiveInterval(int interval)单独设置超时时长。




        Session 超时的概念介绍:客户端两次请求的最大间隔时长




java session下线 java中session是什么意思_java_03


代码示例:


protected void lift3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取 Session 对象
        HttpSession session = request.getSession();

        // 2. 设置 Session 对象的超时时长为3秒
        session.setMaxInactiveInterval(3);

        // 3.获取 Session 对象的超时时长
        int maxInactiveInterval = session.getMaxInactiveInterval();

        response.getWriter().write("设置 Session 中的超时时长成功<br />");
        response.getWriter().write("获取 Session 中的超时时长为:" + maxInactiveInterval + "<br />");

    }

3.3 设置Session对象马上销毁


public void invalidate() 让当前 Session 会话马上超时无效。


代码示例:

protected void deleteLift(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取 Session 对象
        HttpSession session = request.getSession();

        // 2. 让 Session 会话马上销毁
        session.invalidate();

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

    }

4. 浏览器和 Session 之间关联的技术内幕


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


java session下线 java中session是什么意思_java session下线_04


5. 总结

会话
    1) Http是无状态的

        - HTTP 无状态 :服务器无法判断这两次请求是同一个客户端发过来的,还是不同的客户端发过来的
        - 无状态带来的现实问题:第一次请求是添加商品到购物车,第二次请求是结账;如果这两次请求服务器无法区分是同一个用户的,那么就会导致混乱
        - 通过会话跟踪技术来解决无状态的问题。


    2) 会话跟踪技术
        - 客户端第一次发请求给服务器,服务器获取session,获取不到,则创建新的,然后响应给客户端

        - 下次客户端给服务器发请求时,会把sessionID带给服务器,那么服务器就能获取到了,那么服务器就判断这一次请求和上次某次请求是同一个客户端,从而能够区分开客户端

        - 常用的API:
          request.getSession() -> 获取当前的会话,没有则创建一个新的会话
          request.getSession(true) -> 效果和不带参数相同
          request.getSession(false) -> 获取当前会话,没有则返回null,不会创建新的

          session.getId() -> 获取sessionID
          session.isNew() -> 判断当前session是否是新的
          session.getMaxInactiveInterval() -> session的非激活间隔时长,默认1800秒
          session.setMaxInactiveInterval()
          session.invalidate() -> 强制性让会话立即失效
          ....

    3) session保存作用域
      - session保存作用域是和具体的某一个session对应的
      - 常用的API:
        void session.setAttribute(k,v)
        Object session.getAttribute(k)
        void removeAttribute(k)