web 会话机制之 session cookie 详解( 三 )

"); }}获取我们可以通过 httpSession.getAttributeNames() 获取到所有的 session 属性 。
也可以通过 req.getSession().getId() 得到我们的 JSESSIONID 属性 。
package com.github.houbb.simple.servlet;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.io.PrintWriter;import java.util.Enumeration;/** * @author binbin.hou * @since 0.0.2 */@WebServlet("/session/get")public class SessionGetServlet extends HttpServlet {    private static final long serialVersionUID = 491287664925808862L;    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {        // 实际的逻辑是在这里        PrintWriter out = resp.getWriter();        String jsessionId = req.getSession().getId();        out.println("jsessionId: " + jsessionId);        HttpSession httpSession = req.getSession();        Enumeration attrs = httpSession.getAttributeNames();        while (attrs.hasMoreElements()) {            String key = (String) attrs.nextElement();            Object value = httpSession.getAttribute(key);            out.println("key: " + key +"; value: " + value);        }    }}清空清空 session 的操作非常简单 。
直接通过 httpSession.removeAttribute(key) 即可操作 。
package com.github.houbb.simple.servlet;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.io.PrintWriter;import java.util.Enumeration;/** * @author binbin.hou * @since 0.0.2 */@WebServlet("/session/clear")public class SessionClearServlet extends HttpServlet {    private static final long serialVersionUID = 491287664925808862L;    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {        resp.setContentType("text/html;charset=utf-8");        resp.setCharacterEncoding("UTF-8");        PrintWriter out = resp.getWriter();        HttpSession httpSession = req.getSession();        Enumeration attrs = httpSession.getAttributeNames();        while (attrs.hasMoreElements()) {            String key = (String) attrs.nextElement();            httpSession.removeAttribute(key);            out.println("清空 key: " + key);        }    }}上面的代码,为了便于大家学习,已经全部开源:

https://gitee.com/houbinbin/simple-servlet
session 的一些细节相信很多小伙伴读到这里依然是意犹未尽的 。
接下来我们一起考虑几个细节问题 。
会话机制session 创建于服务器端,保存于服务器,维护于服务器端,每创建一个新的Session,服务器端都会分配一个唯一的ID,并且把这个ID保存到客户端的Cookie中,保存形式是以 JSESSIONID 来保存的 。
一点细节不要在意
通过HttpServletRequest.getSession 进行获得HttpSession对象,通过setAttribute()给会话赋值,可以通过invalidate()将其失效 。


推荐阅读