【问题标题】:How to vanish session completely in Servlet?如何在 Servlet 中完全消失会话?
【发布时间】:2015-12-23 11:32:10
【问题描述】:

我有两个 JSP 页面:登录和索引 和三个 Servlet:LoginServlet、LogoutServlet、Profile .现在我只想在会话中有内容时查看我的个人资料。在 LoginServlet 的 post() 中,我编写了设置属性的逻辑,在 LogoutServlet 的 get() 中,我调用了 invalidate() 方法来删​​除会话。现在,当我直接转到个人资料网址而不调用登录页面时,如果 Profile.class 块被执行而不是 else 在 session.getAttribute("name") 中没有任何内容。

Profile的获取方法:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    req.getRequestDispatcher("link.jsp").include(req, resp);  
    HttpSession session = req.getSession(false);
    if (session != null) {
        System.out.println("Session is not null");
        out.print("Hello " + session.getAttribute("name"));
    } else {
        out.print("Please login");
        req.getRequestDispatcher("Login.jsp").include(req, resp);
    }
    out.close();
}

我需要做些什么才能完全消除会话。

【问题讨论】:

  • 为什么要调用 req.getRequestDispatcher("link.jsp").include(req, resp) ?
  • 您发布的代码应该可以工作。在您浏览个人资料之前,您是否关闭了浏览器?如果没有,则会话 cookie 仍被保留。
  • @rickz 是的,我使用了不同的浏览器来确保 cookie 不是它的原因。我更改了 if 条件: if(session.getAttribute("name")!=null) 并且它按照我想要的方式工作。

标签: java jsp session servlets


【解决方案1】:

来自 HttpServletRequest

的文档

getSession() -- 返回与此请求关联的当前 HttpSession,或者,如果没有当前会话并且 create 为 true,则返回一个新会话。

无论会话是否存在,request.getSession() 总是会给你一个 Session 的实例。这就是为什么你的 if 条件总是为真。所以基本上你需要改变你的 if 和 else 条件。而不是检查会话,你应该检查其他类似的东西

if(session.getAttribute("name")!=null)
//perform something

另见

我尝试创建一个 servlet 并测试您指定的内容。我将直接重定向到该 servlet。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        HttpSession session = request.getSession(false);

        if (session != null) {
            System.out.println("Session is not null");  
        } else {
            System.out.println("Session is null");
        }

    }

输出

Session is null

【讨论】:

  • True,getSession() 将始终返回一个实例,如果不存在则创建一个新实例并返回它。但是,我在某处读到 getSession(false) 只有在它已经存在并且永远不会创建新实例的情况下才会返回实例。
  • 我尝试创建一个 servlet 并按照您的指定检查会话。它对我有用。正在编辑我的答案。
【解决方案2】:

在登录类中使用类似的东西:

if (isValidUser(userName, userPass)) {
    request.getSession(true);
    request.getSession.setAttribute("isLogged", true);
}

在 LogoutServlet 类中使用以下代码:

protected void doPost(HttpServletRequest request, ....

    request.getSession().invalidate(); // Vanish session completely
    ....

在 Profile 类中验证用户是否已登录,使用类似:

if ((Boolean) request.getSession.getAttribute("isLogged") != null) {
    ... // user is logged
} else
    redirectToIndexPage();

【讨论】:

  • 我完全明白你的意思。您希望我在 if 块中提供 req.getSession().getAttribute("name") 作为条件。但是,由于我使用的 getSession(false) 方法不应该创建一个新实例,如果它不存在的话。我想知道会话对象不为空的可能原因。
猜你喜欢
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多