我正在JSF中开发一个用户会话控件,以在同一用户登录到我的应用程序时使两个会话中的第一个无效。
例如:如果我有第一个用户会话A
,然后同一用户登录了会话B
,则我想invalidate
进行A
的第一个会话
为此,我实现了一个过滤器,该过滤器将检查同一用户的第二个会话何时登录,然后在会话A
发出的下一个请求中,该程序会使他/她的会话无效。
之后,我想将此会话重定向到注销页面,但是我尝试了很多方法,但似乎无法实现。当我使会话无效时,它会自动转到登录页面,但网站看起来好像坏了。
我会放一张图片。
常用登录图片:Normal Login
登录失败:Broken Login
我已经尝试了StackOverflow的许多答案。例如:
我尝试使用HttpResponse.SendRedirect和Request.getDispatcher,但没有一个起作用。
这里有我的代码:
private HashMap<Integer, SessionObject> mapSessions;
private HttpServletRequest requestHttp;
private HttpSession session;
private HttpServletResponse httpResponse;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
try {
this.requestHttp = (HttpServletRequest) request;
this.httpResponse = (HttpServletResponse) response;
httpResponse.setContentType("text/xhtml");
this.session = requestHttp.getSession(false);
// String requestURI = requestHttp.getRequestURI();
boolean isSessionCanceled = this.executeSessionAlgorithm();
if(isSessionCanceled){
httpResponse.sendRedirect("/app/logout.xhtml");
}
else{
chain.doFilter(request, response);
}
// request.getRequestDispatcher(newURI).forward(request, httpServletResponse);
//HttpServletResponse res = (HttpServletResponse) response;
//res.sendRedirect(loginURL);
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean executeSessionAlgorithm() throws IOException {
if (session != null && session.getAttribute("userId") != null) {
Integer userId = Integer.parseInt(session.getAttribute("userId").toString());
SessionObject sessionObject = mapSessions.get(userId);
if (!existSessionObjectInMap(sessionObject)) {
this.createSessionAndInsertToMap(userId, session.getId());
} else {
return this.checkSessionsComprobationsAndGetIfIsSessionInvalidated(session, sessionObject);
}
}
return false;
}
private boolean existSessionObjectInMap(SessionObject sessionObject) {
return sessionObject != null;
}
private void createSessionAndInsertToMap(Integer userId, String sessionId) {
SessionObject sessionObject = new SessionObject(sessionId, true, false);
mapSessions.put(userId, sessionObject);
}
private boolean checkSessionsComprobationsAndGetIfIsSessionInvalidated(HttpSession session, SessionObject sessionObject) throws IOException {
String currentSessionId = session.getId();
if (sessionObject.isFirstLogSession() && !sessionObject.isSecondLogSession() && !currentSessionId.equals(sessionObject.getSessionId())) {
sessionObject.setSessionId(currentSessionId);
sessionObject.setSecondLogSession(true);
} else if (sessionObject.isFirstLogSession() && sessionObject.isSecondLogSession() && !currentSessionId.equals(sessionObject.getSessionId()) && requestHttp.isRequestedSessionIdValid()) {
sessionObject.setSecondLogSession(false);
this.updateUserHistory(session);
session.invalidate();
return true;
}
return false;
}
无效会话代码正在工作,问题在于它仅仅是重定向。 可能是什么问题呢?可以在应用程序(web.xml)的配置中出现问题吗?
非常感谢您。
PS:这是我在StackOverflow上的第一篇文章,我尽力解释得很好,但是我不太擅长英语写作。