4

In my application I have a quit button, on clicking of which the session for the current user is invalidated by the following piece of the code..

FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

And I redirect the user to a different page.

But now I want if user click on the back button I will take him to the start page of the application instead of the last page visted by him. I have an application phase listener which sets the page cache related headers to 'none', now all I want is to detect that for that user session has been invalidated. But I guess whenever the user is clicking the back button it is creating a new session for the user. Is there any way to prevent it?

Tiny
  • 27,221
  • 105
  • 339
  • 599
user1220373
  • 383
  • 1
  • 9
  • 19

1 Answers1

12

How to detect session has been invalidated in JSF 2?

Check if the user has requested a session ID which is not valid.

HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
    // Session has been invalidated during the previous request.
}

it is creating a new session for the user. Is there any way to prevent it?

Just don't let your application code create the session then. The session will implicitly be created when your application needs to store something in the session, e.g. view or session scoped beans, or the view state of a <h:form>, etc.


I have an application phase listener which sets the page cache related headers to 'none'

A servlet filter is a better place for this. See also Avoid back button on JSF web application

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks a ton, but just one question why you prefer filter than the phase listener for setting the response headers? – user1220373 Jun 26 '12 at 12:16
  • Because it's easier. You don't need the JSF context at all for the job. Also, the example in the linked answer takes care with JSF resources, you really don't want to disable caching for them. – BalusC Jun 26 '12 at 12:18