每当在过滤器/ servlet中,我们用request.getSession( false )
检索会话,这意味着什么?
我知道当session为null时,它可以代表这两种情况中的任何一种。
我在我的应用程序中使用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和身份验证对象null而不是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 :(得分:0)
textview
表示获取会话,但如果没有会话,请不要创建会话。