0

I have been using cookies to share non-sensitive data across sessions. I want to store some lastUsedEntity (a string literal) from the current session at user logout event so that that entity can be read/used at next login session. The said entity belongs to a session bean of my application.

I decided to extract and store this entity in @PreDestroy method of the session bean. The method ran successfully at session timeout of the application. But storing cookie failed because FacesContext.getCurrentInstance() was null in @PreDestroy method, maybe because JSF Lifecycle request-response cycle completed by then. I tried caching FacesContext.getCurrentInstance() in @PostContruct method of my session bean so that I could access faces context cached instance but then I faced another problem java.lang.IllegalStateException at com.sun.faces.context.FacesContextImpl.assertNotReleased because I used FacesContext as instance variable of my session scoped class. I would appreciate if I could get some heads up here or any other better idea in order to persist my old session data for further use in this scenario.

Community
  • 1
  • 1
user2918640
  • 473
  • 1
  • 7
  • 25

1 Answers1

3

There's not necessarily means of a HTTP request when a HTTP session gets expired in server side due to enduser inactivity. The enduser itself is the only one who can send a HTTP request. If there's no HTTP request which invoked the FacesServlet, then there's no FacesContext either. Let alone a HTTP response on which you could return the cookie.

You'd better rethink your logic. E.g. set the cookie immediately on every request, overriding the previous one, if necessary on a specific path and/or with a timestamp in the cookie value. Depending on the concrete functional requirement there may be better ways though as cookies are fully manipulatable by the enduser and you should absolutely not depend critical business logic on that. If it's purely for presentation, it should be okayish, otherwise better store it in the database associated with logged-in user.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Previously I have been doing as you said, setting cookie on each page load (or request). I am working in a multi-page app. Each page with its own id. A page redirects to login page on logout. I have been setting cookie with a key named 'lastOpenedId' in `PostConstruct` method upon landing on each `ViewScoped` page. This id comes from a session scoped service bean. But I had to change it because my actual requirement is to store 'lastExpiredId' instead i.e. I have to track id of a page logged-out due to session timeout. – user2918640 Apr 28 '16 at 08:02
  • That is what I have been thinking as a last resort unless I could come up with something which could be done at web-framework level. – user2918640 Apr 28 '16 at 08:06