0

I have requirement where I have to redirect the page to login.jsp when the session gets expired before user refreshes or clicks button.

We have used JSF for front-end and Java Spring for backend.

I tried the following in my filter, but did not worked:

HttpSession session = request.getSession(false);
if(session==null)
{
    response.sendRedirect("/Login.jsp");
} 
adithyan .p
  • 121
  • 1
  • 3
  • 12

2 Answers2

1

If you want to handle only synchronous POST request on a page while the HTTP session has been expired, the easiest way is just use tag error-page in web.xml

<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/Login.jsp</location>
</error-page>

but if your app has any ajax request, I suggest to implement a custom ExceptionHandler, please see in Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request

JJ Witaya
  • 11
  • 3
  • how about implementing the HttpSessionListener by creating custome class? will servlet listen this class if session got expired, if so i cna forward to login page from my customer class rgt ? – adithyan .p May 26 '17 at 06:12
  • I think (doesn't try it), the browser's not gonna redirect to Login page because when the session is expired, sessionDestroyed() will be triggered immediately, so this's not the part of HTTP request activity, by the way you still use your servlet filter but try this code `if(session != null && !session.isNew()) { chain.doFilter(request, response); } else { response.sendRedirect("/login.jsp"); }` – JJ Witaya May 26 '17 at 06:39
  • i tried the above code from my filter but it did not redirected – adithyan .p May 26 '17 at 09:05
0

When you do:

HttpSession session = request.getSession(false);

You're creating a session object, and it won't be null. So it'll never enter inside this if:

if(session==null)

You can just change this if to:

if(session!=null)
  • i want to check if session expired, how do i do that? – adithyan .p May 26 '17 at 06:10
  • Take a look [here](https://stackoverflow.com/questions/2070179/how-to-check-session-has-been-expired-in-java) or [here](https://stackoverflow.com/questions/1026846/how-to-redirect-to-login-page-when-session-is-expired-in-java-web-application) –  May 26 '17 at 11:59