【问题标题】:How to logout session using invalidate() in servlet [duplicate]如何在servlet中使用invalidate()注销会话[重复]
【发布时间】:2014-05-02 06:02:21
【问题描述】:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        HttpSession session = request.getSession();
        if(session != null)
        {
            try
            {
                response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
                response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
                response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
                response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
                session.setAttribute("admin_name",null);
                session.invalidate();
                response.sendRedirect("login.jsp");
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
                System.out.println(e);
            }

        }
        else
        {


        }
    }

这是我的 servlet。我将注销我使用名称 admin_name 创建的会话。当我注销会话时,它成功地点击了登录页面。但是当我按下后退按钮时,它会转到上一页。即使我使该会话无效,我也不明白为什么会发生这些。但是当我刷新该页面时,它会再次点击登录页面。

这是我在jsp页面中使用的代码。

<%
        String name = null;
        if (session.getAttribute("admin_name") == null) {
            response.sendRedirect("login.jsp");
        } else {
            name = (String) session.getAttribute("admin_name");
        }
    %>

【问题讨论】:

  • 您无需从即将失效的会话中删除内容。它将变得无法访问,并且 (a) 因此会受到 GC 的约束,并且 (b) 属性也将变得无法访问和无法访问。

标签: jsp session servlets invalidation


【解决方案1】:

调用.invalidate 方法后,会话立即为invalidated

来自文档,

invalidate

void invalidate()
Invalidates this session then unbinds any objects bound to it.

从你的问题

I didn't understood why these happen even if i invalidate that session. 

but when i refresh that page it will again hit the login page.

这是因为页面是从浏览器缓存中加载的,即使转到上一页也无法从加载的页面发送任何请求

更新

查看How to clear browser cache using java

希望这会有所帮助!

【讨论】:

  • 我也这样做了。请参阅我更新的问题。但同样的问题。告诉我哪里错了
  • this线程
【解决方案2】:

在这种情况下,您的会话已成功过期。这是您浏览器中的功能,当您单击返回按钮时,它会显示捕获的网页副本。因此,如果您单击刷新页面,您将不会再次看到该页面。在这种情况下,您的网页将不会被处理,因为会话已过期并将再次进入登录页面。

【讨论】:

  • 所以我需要做些什么来避免这个问题。
  • @Shan 检查我的更新答案
猜你喜欢
  • 2013-03-14
  • 2016-08-09
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多