This is not an exception to Nullpointer.
This is an exception to the illegal state.
This happens when the session is invalid / expired and you are trying to access it.
The session becomes invalid as follows.
session.invalidate();
After calling invalidate, you cannot use the session.
The session ends when the timeout expires. When they expire, if you try to use it, it will throw the same exception.
Here's how you can manually set the timeout.
set the timeout in web.xml. This is set in minutes.
<session-config> <session-timeout>30</session-timeout> </session-config>
Or you can install it in your java.
public void setMaxInactiveInterval(int interval) session.setMaxInactiveInterval(30*60);
Here we indicate the time in seconds between client requests before the servlet container cancels this session. A negative time indicates that the session should never expire.
Make sure the operation you are doing does not take longer than the wait time. Otherwise, you will have to reset the value.
EDIT:
A clean recovery is not possible. The session will be invalidated / invalid and you will need to create a new session and re-populate the data. Typically, people are redirected to an alternate PAge error instead of showing a stack trace. "Your session has expired. Please log in again."
Use request.isRequestedSessionIdValid () to determine if the session identifier is valid.
HttpSession session =httpReg.getSession(false); if( !request.isRequestedSessionIdValid() ) { //comes here when session is invalid. // redirect to a clean error page "Your session has expired. Please login again." }
Another option is to use the IllegalExceptionState handle with try catch
HttpSession session =httpReg.getSession(false); try { if(session != null) { Date date = new Date(session.getLastAccessedTime()); } } catch( IllegalStateException ex ) {
Side note: If you have a process that takes a long time and the sessions are synchronized (for example: parsing really large data records). You should consider putting them out of your web application and using simple java to run them as a process.