Issue
I have a single page application, written using Jquery, java is used at the back-end.
After session timeout, If user do some activity which triggers Ajax call, then user should be redirected to login screen.
If It would have been an another page request, then following solution might have worked, but as it is Ajax call, redirection just give another response to success function.
I Tried
In main Filter
HttpSession session = request.getSession(false); if(session != null && !session.isNew()) { chain.doFilter(request, response); }else { response.sendRedirect("/login.jsp"); }
Refreshing the tab by sending below header on ajax call, from inside main filter
httpResponse.setHeader("Refresh", "0; URL=" + targetUrl);
Solution
server side: Add a filter, which will be processed for every single request, inside that filter's doFilter method add following code:
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession(false);// don't create if it doesn't exist
if(session == null || session.isNew()) {
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // status code is 401
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
client side: configure ajax such that when it receives any response with status code 401, it reloads the tab or change the window.location. This is how it can be done using jquery:
$(window).load(function(){
$.ajaxSetup({
statusCode: {
401: function(){
location.reload(); // or window.location="http://www.example.com"
}
}
});
});
for me reloading was enough, to take the user to login screen
Answered By - sanjiv saini
Answer Checked By - Timothy Miller (JavaFixing Admin)