2016-06-12 80 views
0

无论何时在filter/servlet中,我们用request.getSession(false)检索会话,这意味着什么?会话null,它是什么意思?

我知道当会话为空时,它可以表示任何这两种情况。

  1. 没有与请求相关联的JSESSION Id cookie,请求是新请求。
  2. 与JSESSION id关联的会话已过期?

我在我的应用程序中使用Spring-Security。我创建了一个拦截所有请求的过滤器,检查是否有会话和与请求关联的身份验证对象,如果没有,我假设请求是全新的,并创建一个新会话并创建一个空白身份验证对象与NULL主体和空白权限列表,并将验证设置为true。

HttpSession session = httpRequest.getSession(false); 
     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 

    if(session == null && auth == null) { 
     LOGGER.debug("In AuthenticationFilter | In doFilter | Session and Authentication are both null."); 
     session = httpRequest.getSession(true); 

     auth = CookieAuthentication.createBlankAuthentication(); 
     auth.setAuthenticated(true); 
     SecurityContextHolder.getContext().setAuthentication(auth); 

     chain.doFilter(req, res); 
    } 
    else if(session == null && auth != null) { 
     LOGGER.debug("In AuthenticationFilter | In doFilter | Session is null but authentication is not."); 
     LOGGER.info("In AuthenticationFilter | Returning Response."); 

     Response response = new Response(); 

     response = new Response(); 
     response.setMessage("Session Has Expired."); 
     response.setFlag("SE"); 

     httpResponse.setStatus(401); 

     try { 
      httpResponse.getWriter().write(response.toJSON()); 
      httpResponse.getWriter().flush(); 
     } 
     catch (IOException e) {    
      LOGGER.error(e.getMessage()); 
     } 
    } else if (session != null && auth != null) { 
     LOGGER.debug("In AuthenticatorFilter | In doFilter | Session and Authentication are not null. ");   
     chain.doFilter(req, res); 
    } else { 

     /** 
     * Some Fatal error. 
     * We shouldn't be here. 
     */ 

     Response response = new Response(); 

     response = new Response(); 
     response.setMessage("Un Authenticated"); 
     response.setFlag("UA"); 

     httpResponse.setStatus(401); 

     try { 
      httpResponse.getWriter().write(response.toJSON()); 
      httpResponse.getWriter().flush(); 
     } 
     catch (IOException e) {    
      LOGGER.error(e.getMessage()); 
     } 

    } 

什么是各种情况下,当我可以接收会话空和认证对象null和非空。

我的假设如下。

Session : null, authenticatin : null -> Fresh Request. 
Session : null, authentication : not-null -> Expired Session. 
Session : not-null, authentication : null -> Shouldn't happen normally. 
Session : not-null, authentication : not-null -> Previously authenticated request. 

请让我知道我对这个概念的误解。 以及其他这些,我想知道如何区分会话不存在,并且当我接收会话为空时已经过期。

回答

0

getSession(false)表示获得会话,但如果没有会话,则不创建会话。