【问题标题】:Cannot unset session in java servlet无法在 java servlet 中取消设置会话
【发布时间】:2017-04-11 11:49:39
【问题描述】:

我有一个logout.jsp页面,用来使会话失效,下面是它的内容:

session.invalidate();
response.sendRedirect("login.jsp");

在我的 profile.jsp 页面中,我想检查是否设置了会话变量,并根据它允许用户浏览页面或重定向回登录页面(如果未设置会话变量)

if(request.getSession(false)==null){
    response.sendRedirect("login.jsp");
}

但问题是,这不能像直接从地址栏打开 profile.jsp 页面那样工作,即使没有用户登录,它也会在没有重定向到登录页面的情况下打开。进一步打印request.getSession(false) I获取输出org.apache.catalina.session.StandardSessionFacade@ad4a7e。我不知道这是什么,也没有在互联网上找到任何关于它的信息。那么如何解决这个问题。

编辑:

我将其对象用作会话变量的类“用户”实现了可序列化,这可能是我面临的问题的原因。

我不被允许发表评论,所以我在这里提到了它。 我使用接受 cookie 的 chrome....进一步我在 Microsoft Edge 中尝试过同样的方法,但它仍然是一样的

【问题讨论】:

  • 一个 JSP 自动创建一个会话,除非你告诉它不要创建一个。通常我们会在 session 中放置一个属性,然后检查该属性是否被设置。
  • 是的,我也尝试过:if(session.getAttribute("user")==null){ response.sendRedirect("login.jsp");} System.out.println(session.getAttribute("user")); 这里的用户是会话变量属性,控制台输出是mypack.user@1ad20a7,其中 mypack 是包的名称我有一个名为“用户”的类。我将其对象用作会话变量
  • 它没有重定向
  • 我复制并粘贴了您的代码。这个对我有用。您还应该在两个页面中添加 以查看会话是否相同。
  • session.getId() 在我什至没有登录的 login.jsp 页面中给出了不同的值。

标签: java jsp session servlets


【解决方案1】:

我假设您已经创建了用于登录和注销的 servlet,然后您可以从相应的 servlet 重定向到该页面: 这可能是您的登录 servlet 代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String email = request.getParameter("email");
    String password = request.getParameter("password");
    HttpSession session = request.getSession();
    session.setAttribute("userName", email);
    session.setAttribute("password", password);
   getServletContext().getRequestDispatcher("/profile.jsp").forward(request, 
    response);
    }

这可以是您的 profile.jsp 页面代码来检查会话:

 <%
if(!(request.getSession(true).getAttribute("userName").toString()).isEmpty()){
  String firstName = (String)request.getAttribute("firstName");
 String lastName = (String)request.getAttribute("lastName");
 }else{%>
 <jsp:forward page = "Login.jsp" />
<% }%>

您可以从注销页面向 logoutservlet 发送请求。而且,这可以是您的 logoutservlet 代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    session.invalidate();
    out.println("Logout Successful");
    out.println("Username : "+session.getAttribute("userName"));
    out.println("Password : "+session.getAttribute("password"));

}

之后,当我从会话中获取凭据时,我会得到这些字段的空值。

【讨论】:

  • &lt;%=request.getSession(true).getAttribute("userName").toString().isEmpty()%&gt; 返回 false...我尝试了上述方法,在我的注销页面中 request.getSession(false) 返回 null 但在打开 profile.jsp 页面(未登录)时返回 true...如果您想查看我的任何特定文件,可以提及我将在此处添加。
猜你喜欢
  • 2017-01-06
  • 2011-10-15
  • 2013-07-16
  • 2014-04-03
  • 2015-10-05
  • 2017-08-09
  • 2018-11-03
  • 2015-10-30
  • 2012-02-20
相关资源
最近更新 更多