How to redirect to Login page when Session is expired in Java web application?
Solution 1
You could use a Filter and do the following test:
HttpSession session = request.getSession(false);// don't create if it doesn't exist
if(session != null && !session.isNew()) {
chain.doFilter(request, response);
} else {
response.sendRedirect("/login.jsp");
}
The above code is untested.
This isn't the most extensive solution however. You should also test that some domain-specific object or flag is available in the session before assuming that because a session isn't new the user must've logged in. Be paranoid!
Solution 2
How to redirect to Login page when Session is expired in Java web application?
This is a wrong question. You should differentiate between the cases "User is not logged in" and "Session is expired". You basically want to redirect to login page when user is not logged in. Not when session is expired. The currently accepted answer only checks HttpSession#isNew()
. But this obviously fails when the user has sent more than one request in the same session when the session is implicitly created by the JSP or what not. E.g. when just pressing F5 on the login page.
As said, you should instead be checking if the user is logged in or not. Given the fact that you're asking this kind of question while standard authentication frameworks like j_security_check
, Shiro, Spring Security, etc already transparently manage this (and thus there would be no need to ask this kind of question on them), that can only mean that you're using a homegrown authentication approach.
Assuming that you're storing the logged-in user in the session in some login servlet like below:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@EJB
private UserService userService;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/home");
} else {
request.setAttribute("error", "Unknown login, try again");
doGet(request, response);
}
}
}
Then you can check for that in a login filter like below:
@WebFilter("/*")
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURI = request.getContextPath() + "/login";
boolean loggedIn = session != null && session.getAttribute("user") != null;
boolean loginRequest = request.getRequestURI().equals(loginURI);
if (loggedIn || loginRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURI);
}
}
// ...
}
No need to fiddle around with brittle HttpSession#isNew()
checks.
Solution 3
you can also do it with a filter like this:
public class RedirectFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
//check if "role" attribute is null
if(req.getSession().getAttribute("role")==null) {
//forward request to login.jsp
req.getRequestDispatcher("/login.jsp").forward(request, response);
} else {
chain.doFilter(request, response);
}
}
}
Solution 4
Check for session is new.
HttpSession session = request.getSession(false);
if (!session.isNew()) {
// Session is valid
}
else {
//Session has expired - redirect to login.jsp
}
Solution 5
Inside the filter inject this JavaScript which will bring the login page like this. If you don't do this then in your AJAX call you will get login page and the contents of login page will be appended.
Inside your filter or redirect insert this script in response:
String scr = "<script>window.location=\""+request.getContextPath()+"/login.do\"</script>";
response.getWriter().write(scr);
Related videos on Youtube
Comments
-
Veera about 4 years
I'm running a web application in JBoss AS 5. I also have a servlet filter which intercepts all the requests to the server. Now, I want to redirect the users to the login page, if the session has expired. I need to do this 'isSessionExpired()' check in the filter and need to redirect the user accordingly. How do I do it? I'm setting my session time limit in web.xml, as below:
<session-config> <session-timeout>15</session-timeout> </session-config>
-
Mr_and_Mrs_D almost 12 yearsWhy not use a SessionListener and redirect on session destroyed ?
-
BalusC almost 9 years@Mr_and_Mrs_D: because there's not necessarily a HTTP request available during session destroy.
-
-
Alex over 12 yearsYour snippet is susceptible to null pointer exceptions. Passing false to
getSession
will not create a session if one doesn't exist and will therefore return null. -
BalusC over 12 yearsCopypasted code is not DRY. Use a Filter. See also stackoverflow.com/questions/3177733/…
-
Kong almost 11 yearsUtterly hideous solution!
-
Jaikrat over 10 years@Yeti, then why to check isNew() at all when we can do the same with one null check!! :)
-
codefreaK over 9 years@zkarthik Nullpointer exception in case of session timeouts "if only it was this easy" the as null.isNew() will occur when session is equal to null which will trigger exception
-
Swaprks about 9 yearsThis can also throw a NULL pointer exception when you try to read the attribute if getSession returns null.
-
The Java Guy almost 9 yearsAlso you may have some pages where user is not logged in. i.e registration pages where you wont get any role.
-
MacGyver over 8 yearsYes, that's true. That would be a 3rd argument (value being passed in) for the optional 3rd parameter (for the method definition) in the method, but doFilter is a method of the object "chain" in your code. Where is "chain" set above that line of code in your source code?
-
Alex over 8 yearsI don't know what you're referring to with regards to optional 3rd parameters. The
chain
variable is passed in to your implementation ofdoFilter
, by the container. It is implied in this answer that the code is inside thedoFilter
. -
Rohit over 7 years@MacGyver chain is the object of FilterChain Class that is present in doFilter method.