• JavaWeb Session会话


    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:
    1. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    2. <html>
    3. <head>
    4. <meta http-equiv="pragma" content="no-cache"/>
    5. <meta http-equiv="cache-control" content="no-cache"/>
    6. <meta http-equiv="Expires" content="0"/>
    7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    8. <title>Sessiontitle>
    9. <base href="http://localhost:8080/14_session/"/>
    10. <style type="text/css">
    11. ul li {
    12. list-style: none;
    13. }
    14. style>
    15. head>
    16. <body>
    17. <iframe name="target" width="500" height="500" style="float: left;">iframe>
    18. <div style="float: left;">
    19. <ul>
    20. <li><a href="sessionServlet?action=createSession" target="target">Session的创建和获取(id号、是否为新创建)a>li>
    21. <li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储a>li>
    22. <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取a>li>
    23. <li>Session的存活li>
    24. <li>
    25. <ul>
    26. <li><a href="" target="target">Session的默认超时及配置a>li>
    27. <li><a href="" target="target">Session3秒超时销毁a>li>
    28. <li><a href="" target="target">Session马上销毁a>li>
    29. ul>
    30. li>
    31. <li><a href="" target="target">浏览器和Session绑定的原理a>li>
    32. ul>
    33. div>
    34. body>
    35. html>

    BaseServlet:

    1. public abstract class BaseServlet extends HttpServlet {
    2. @Override
    3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    4. doPost(req, resp);
    5. }
    6. @Override
    7. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    8. // 解决post请求中文乱码问题
    9. // 一定要在获取请求参数之前调用才有效
    10. request.setCharacterEncoding("UTF-8");
    11. response.setContentType("text/html;charset=UTF-8");
    12. String action = request.getParameter("action");
    13. // 获取 action 业务鉴别字符串,获取相应的业务 方法反射对象
    14. try {
    15. Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
    16. // 调用目标业务 方法
    17. method.invoke(this, request, response);
    18. } catch (Exception e) {
    19. // e.printStackTrace();
    20. }
    21. }
    22. }

    SessionServlet程序:

    1. @WebServlet(name = "SessionServlet", value = "/sessionServlet")
    2. public class SessionServlet extends BaseServlet {
    3. /**
    4. * 创建Session对象,并查看其是否为第一次创建及其id值
    5. *
    6. * @param request
    7. * @param response
    8. * @throws ServletException
    9. * @throws IOException
    10. */
    11. protected void createSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    12. // 1. 获取 Session 对象
    13. HttpSession session = request.getSession();
    14. // 2. 查看创建的 Session 对象是否为新
    15. boolean aNew = session.isNew();
    16. // 3.查看创建的 Session 对象的ID值
    17. String id = session.getId();
    18. response.getWriter().write("已创建了 Session 对象
      "
      );
    19. response.getWriter().write("查看创建的 Session 对象是否为新:" + aNew + "
      "
      );
    20. response.getWriter().write("查看创建的 Session 对象的ID值:" + id + "
      "
      );
    21. }
    22. /**
    23. * 往Session中保存数据
    24. *
    25. * @param request
    26. * @param response
    27. * @throws ServletException
    28. * @throws IOException
    29. */
    30. protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    31. // 1. 获取 Session 对象
    32. HttpSession session = request.getSession();
    33. // 2.向 Session 中保存数据
    34. session.setAttribute("key", "value");
    35. response.getWriter().write("已经往 Session 中保存了数据
      "
      );
    36. }
    37. /**
    38. * 获取Session中的数据
    39. *
    40. * @param request
    41. * @param response
    42. * @throws ServletException
    43. * @throws IOException
    44. */
    45. protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    46. // 1. 获取 Session 对象
    47. HttpSession session = request.getSession();
    48. // 2. 获取 Session 域中的数据
    49. Object key = session.getAttribute("key");
    50. response.getWriter().write("获取 Session 中的数据为:" + key + "
      "
      );
    51. }
    52. }

    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 分钟。
            
                    30
            

    代码示例:

    1. protected void defaultLift(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    2. // 1. 获取默认超时时长 Session 对象
    3. HttpSession session = request.getSession();
    4. // 2. Session 对象的超时时长
    5. int maxInactiveInterval = session.getMaxInactiveInterval();
    6. response.getWriter().write("获取 Session 中的默认超时时长为:" + maxInactiveInterval + "
      "
      );
    7. }

    结果:

     

            如果说。你希望你的 web 工程,默认的 Session 的超时时长为其他时长。你可以在你自己的 web.xml 配置文件中做以上相同的配置。就可以修改你的 web 工程所有 Seession 的默认超时时长。
    示例:
    1. <session-config>
    2. <session-timeout>20session-timeout>
    3. session-config>

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

     

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

            如果你想只修改个别 Session 的超时时长。就可以使用上面的 APIsetMaxInactiveInterval(int interval)来进行单独的设置。
            session.setMaxInactiveInterval(int interval)单独设置超时时长。
            Session 超时的概念介绍:客户端两次请求的最大间隔时长

     

    代码示例:
    1. protected void lift3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    2. // 1. 获取 Session 对象
    3. HttpSession session = request.getSession();
    4. // 2. 设置 Session 对象的超时时长为3秒
    5. session.setMaxInactiveInterval(3);
    6. // 3.获取 Session 对象的超时时长
    7. int maxInactiveInterval = session.getMaxInactiveInterval();
    8. response.getWriter().write("设置 Session 中的超时时长成功
      "
      );
    9. response.getWriter().write("获取 Session 中的超时时长为:" + maxInactiveInterval + "
      "
      );
    10. }

    3.3 设置Session对象马上销毁

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

    代码示例:

    1. protected void deleteLift(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    2. // 1. 获取 Session 对象
    3. HttpSession session = request.getSession();
    4. // 2. 让 Session 会话马上销毁
    5. session.invalidate();
    6. response.getWriter().write("Session 已经设置为超时(无效)");
    7. }

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

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

     

  • 相关阅读:
    JAVA毕业设计Vue网上书籍购买商城登录计算机源码+lw文档+系统+调试部署+数据库
    程序员提高效率的工具和习惯分享
    idea由artifactId快速找到对应的maven依赖配置复制使用
    【题解】[NOIP2015]扫雷游戏(Java & C++)
    多模态 —— Learnable pooling with Context Gating for video classification
    Cpolar+Tipas:在Ubuntu上搭建私人问答网站,为您提供专业的问题解答
    【LeetCode刷题-双指针】--259.较小的三数之和
    AWS-Basic-S3
    软件工程与计算(十八)代码设计
    Java程序员:三个月刷完1000道面试真题,没想到老板直接给我升职了
  • 原文地址:https://blog.csdn.net/weixin_65637841/article/details/126067887