问题
The problem: I am on some page of my application and go away for a while. Coming back and clicking on a link I get a "Unable to restore viewID" message. Same on hitting refresh.
I can start a new session, but I have to manually edit the URL as follows:
Active address window:
http://localhost:8080/myapp/index.xhtml?windowId=e9d
into
http://localhost:8080/myapp/index.xhtml
Then a new session is established, and the user has to log in again which is what I want.
In researching how to deal with this, I see a lot of "solutions" that basically keep the session alive by using client-side Javascript to send requests periodically to keep the session alive. Personally I do not consider this a desirable solution.
What I want is when the session times out, all subsequent requests to any non-public page needs to be directed to index.xhtml. References to pages that don't require login should go through with a new session object. Preferably this would be handled using only JSF 2 defined facilities, but I don't mind writing a Servlet filter if that is what it takes.
Can anyone provide a link to a how-to that I missed?
回答1:
Do it in a Filter, yes. You could use HttpServletRequest#getRequestedSessionId() to check if the client has sent a session cookie and HttpServletRequest#isRequestedSessionIdValid() to check if it is still valid (i.e. the session hasn't been expired in the server side):
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletRequest res = (HttpServletResponse) response;
if (req.getRequestedSessionId() != null && !req.isRequestedSessionIdValid()) {
res.sendRedirect(req.getContextPath() + "/index.xhtml");
} else {
chain.doFilter(request, response);
}
}
But, that brings up another question, how exactly are you filtering logged-in users? If the session is expired, then the user is not logged-in anymore, right? You could instead also just check in the filter if the user is logged-in or not.
来源:https://stackoverflow.com/questions/7796612/what-is-the-method-for-gracefully-handling-session-timeout