JSF - maintain a session for an indefinite period of time

Is there a way to keep the page session active without resorting to sending state to the client? I cannot set STATE_SAVING_METHOD to client , and I would prefer not to use a4j:keepalive .

I tried using a simple hidden iframe that is sent to the Bean, but it is not valid on the main page.

I am using JSF 1.2 and myfaces.

This should get around a ViewExpiredException on a page that does not require the user to log in. Most existing sites require the user to log in.

+4
source share
2 answers

Deploy ajax polling as a “heartbeat” to save the session. In the simplest case, you can achieve this as follows with a little jQuery to avoid 100-line boilerplate code, to make it work in all different browsers that the world knows about:

 <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { setInterval(function() { $.get("${pageContext.request.contextPath}/poll"); }, ${(pageContext.session.maxInactiveInterval - 10) * 1000}); }); </script> 

${pageContext.session.maxInactiveInterval} prints the remaining seconds, while the session does not yet live according to the server-side configuration (which, by the way, is controlled by <session-timeout> in web.xml ) and is subtracted with 10 seconds, only to be on time before it automatically expires and converts to milliseconds to match what setInterval() expects.

$.get() sends an ajax GET request to the given URL. In the above example, you need to map the servlet to the URL pattern /poll and basically use the doGet() method:

 request.getSession(); // Keep session alive. 

It should be.

+10
source

BalusC's answer helped me satisfy this requirement in my application, but since I use PrimeFaces, I would like to share how BalusC responds to the inspirational code that I use for this.

xhtml page

 <p:poll listener="#{pf_usersController.keepUserSessionAlive()}" interval="#{session.maxInactiveInterval - 10}" /> 

bean

 public void keepUserSessionAlive() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); request.getSession(); } 

as always, thanks, BalusC!

EDIT: Endiser put this to the test this morning and it works great! my application usually forces the session timeout 15 minutes after the page is completely refreshed (redirect to sessionExpired.xhtml via meta refresh based on session.maxInactiveInterval and session timeout values ​​in web.xml); if a user makes a bunch of AJAX requests on one page, the session will time out, because AJAX! = refresh the full page, but this code allowed enduser to "save the session" and enduser on the payroll page in the application, and the session remained alive from 1 to 2 hours! :)

+3
source

Source: https://habr.com/ru/post/1390098/


All Articles