I have a session validation Filter which logs off the user when session is expired.
Here is a piece of code but this is not working. Not working means this is not redirecting to the login page even if the session expires.
Please help me to resolve this issue.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
HttpSession s = req.getSession(false);
if (s==null)
{
//redirect to login page with session expiry message
} else {
chain.doFilter(request, response);
}
}
Best Answer
This makes honestly no utter sense. If you store the logged-in user as an attribute of the session and intercept the "logged-in" status based on the presence of the logged-in user in the session, then you do not need to manually logout the user at all when the session is expired. When the session expires, all its attribtues will get lost anyway and hence the user will be "automagically" logged out.
Here's an example of how you can login the user in the
doPost()
of a servlet which is invoked by a POST submit of the login form JSP.You see, when the login is valid, the user is stored as a session attribute. The remnant of your code could just check if it is null or not to determine if the user is logged in. Whenever the session expires, it automatically becomes null.
I have no idea what you're trying to do since the initial functional requirement makes no sense. However, there exist two common functional requirements related to session expiration and the login page. I guess that you actually need either one of them:
"How do I redirect the visitor to the login page when he requests a page which is restricted to logged-in users?"
You need to create a filter and map it on the (common) URL pattern of the restricted page(s). In the filter, just check if the user is present in session and then continue the chain, else redirect to login page.
"How do I automatically redirect the currently opened page to the login page when the session expires?"
Use the
<meta>
refresh in combination withHttpSession#getMaxInactiveInterval()
.This will automatically redirect the current page to the given
url
whenever the session expires. The${pageContext.session.maxInactiveInterval}
expression will inline the session expiration time in seconds, which is exactly what thecontent
attribute needs.