【发布时间】: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) 并且它按照我想要的方式工作。