2015-01-31 3 views
1

Я создал приложение для входа в java, в котором все работает нормально, но когда я нажимаю кнопку выхода из системы, он успешно выходил из системы и перенаправлялся на index.jsp, но на странице index.jsp, если я печатаю значение сеанса, то оно печатает то же самое, я не знаю, почему ?? Однако при выходе из системы я убью сеанс. Ниже приведен код: пожалуйста, укажите возможную причину:После завершения сеанса сеанс не заканчивается

на странице index.jsp ниже приведен код, который проверяет, существует ли сессия сессии. После выхода из системы он печатает "ISession не равно нулю" ...

<% 
      if (session == null) 
      { 
       System.out.println("session is null"); 
       session.removeAttribute("username"); 
       session.removeAttribute("uniqueID"); 
       session.invalidate(); 
      } 
      else if(session != null) 
      { 
       System.out.println("isession is not null"); 
       System.out.println(session); 
      } 

     %> 

loginServlet.java

String name = ""; 
      JSONObject obj = result_array.getJSONObject(0); 
      String res = obj.get("result").toString(); 
      HttpSession session = null; 
      if (res.equals("true")) { 
       try { 
        name = obj.get("name").toString(); 
        session = request.getSession(true); 
        session.setAttribute("username", name); 
        session.setAttribute("uniqueID", uname); 
        //setting session to expiry in 15 mins 
        session.setMaxInactiveInterval(15*60); 
        Cookie userName = new Cookie("user", uname); 
        userName.setMaxAge(15*60); 
        response.addCookie(userName); 

        if("0".equals(obj.get("role").toString())) 
        { 
         session.setAttribute("role", "user"); 
         response.sendRedirect("home.jsp");       
        }       
        else if("1".equals(obj.get("role").toString())) 
        { 
         session.setAttribute("role", "admin"); 
         response.sendRedirect("AdminHome.jsp");       
        } 
       } 
       catch (JSONException ex) 
       { 
        System.out.println(getClass().getName()+" = " +ex.toString()); 
        this.context.log(ex.toString()); 
       } 

logoutservlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     response.setContentType("text/html"); 
//  Cookie[] cookies = request.getCookies(); 
//  if (cookies != null) { 
//   for (Cookie cookie : cookies) { 
//    if (cookie.getName().equals("JSESSIONID")) { 
//     System.out.println("JSESSIONID=" + cookie.getValue()); 
//     break; 
//    } 
//   } 
//  } 
     Cookie loginCookie = null; 
     Cookie[] cookies = request.getCookies(); 
     if (cookies != null) { 
      for (Cookie cookie : cookies) { 
       if (cookie.getName().equals("user")) { 
        loginCookie = cookie; 
        break; 
       } 
      } 
     } 
     if (loginCookie != null) { 
      loginCookie.setMaxAge(0); 
      response.addCookie(loginCookie); 
     } 
     PrintWriter out = response.getWriter(); 
     HttpSession session = request.getSession(false); 
     if (session != null) { 
      session.removeAttribute("username"); 
      session.removeAttribute("uniqueID"); 
      session.removeAttribute("role"); 
      session.invalidate(); 
     } 
     out.print("You have Succefully logged out "); 
     response.sendRedirect("index.jsp"); 
     out.flush(); 
     out.close(); 
    } 
} 

ответ

0

По умолчанию сеанс автоматически создается JSP, если он уже существует, конечно. Итак, после выхода из системы, когда вы проверяете неявный объект session, это новый.

Вы можете проверить это, напечатав

<%= session.isNew() %> 

Чтобы отключить это для конкретной JSP, необходимо установить атрибут вашей page директивы session.

<%@ page session="false" %> 

Это кажется ненужным, хотя из-за вошедшего в состояние/выход всегда можно определить по наличию атрибута сеанса, а не недействительность самой сессии.

Смежные вопросы