我的JSP项目中有三个简单的HttpServlet类,即“ LoginServlet”,“ LogoutServlet”和“ ProfileServlet”。
我认为以下两个最后两个servlet是有问题的。
@SuppressWarnings("serial") public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); HttpSession session=request.getSession(false); session.invalidate(); request.getRequestDispatcher("link.jsp").include(request, response); out.print("You are successfully logged out!"); out.close(); } }
和
@SuppressWarnings("serial") public class ProfileServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); request.getRequestDispatcher("link.jsp").include(request, response); HttpSession session = request.getSession(false); if (session != null) { String name = (String) session.getAttribute("name"); out.print("Hello, " + name + " Welcome to Profile"); } else { out.print("Please login first"); request.getRequestDispatcher("login.html").include(request, response); } out.close(); } }
和link.jsp:
<% HttpSession nsession = request.getSession(false); if(nsession == null) { %> <a href="login.html">Login</a> <% } else { %> <a href="LogoutServlet">Logout</a> <% } %> <a href="ProfileServlet">Profile</a> <hr/>
问题是用户登录时,单击“注销”链接并调用“ LogoutServlet”时,会话未正确无效,并且ProfileServlet仍打印出来
"Hello, null Welcome to Profile"
而不是重定向到“ login.html”页面,因为该会话仍不为null。结果,“登录”链接未显示在“ link.jsp”页面上。这使用户无法尝试再次登录。
编辑: 为了使问题得到澄清,我做了一个新的html页面并更新了servlet以执行此操作
request.getRequestDispatcher("link.html").include(request, response);
和“ link.html”。
<a href="login.html">Login</a> <a href="LogoutServlet">Logout</a> <a href="ProfileServlet">Profile</a> <hr/>
有趣的是,这正是我想要的!我想问题是
request.getRequestDispatcher("link.jsp").include(request, response);
但是我无法解释为什么…
在JSP中,默认情况下会创建新会话(如果不存在),因此您将始终获得非null会话。您可以通过在页面上添加以下页面指令来禁用它:
<%@ page session="false" %>