Session variable is null when accessed second time - java

I am new to this forum. I am designing a JSP-Servlet application and using session variables to store objects.
Problem is, when I access the session variables for second time it returns null.
Here is the flow of my app -
I have a jsp page with mulitple link buttons. When user clicks on any button a servlet is called with respective parameters. eg 1 is passed if button1 is clicked, 2 if button2 is clicked,etc.
Servlet gets an arraylist from session variable which is already created earlier and depending on requested parameter gets the data from arraylist, processes it and sends response to another jsp say jsp2.
jsp2 also has similar link buttons and should do the same task. When the same Servlet is called from jsp2 or even if the page is refreshed, the session variable is null this time.
In my web.xml file under the session-config tag I have set the timeout to -1 so that session never expires.
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
In the servlet I get the session variable as-
HttpSession session = request.getSession(false);
ArrayList<String> list = new ArrayList<String>();
list = (ArrayList<String>)session.getAttribute("mylist");
When the servlet is called second time or even if the page is refreshed the list is null.
I put few lines to check if session is valid-and it prints the second time.
if(!request.isRequestedSessionIdValid()) {
System.out.println("Session is Expired !!");
}
and the session.getAttribute("mylist") returns NullPointerException.
I am sure that I have not used session.invalidate() anywhere by chance to end the session.
I dont understand what is going wrong..can someone can explain me ?
Many thanks in advance.

You would need to try with getSession(true) for the first time or getSession().
False argument will not return session if the session doesn't exist. Only for the first time you would need to supply true in to the getSession call.
HttpSession session = request.getSession(true);
According to servlet specification,
HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no
current session and create is true, returns a new
session.
If create is false and the request has no valid HttpSession, this method
returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is
using cookies to maintain session integrity and is asked to create a
new session when the response is committed, an IllegalStateException
is thrown.
Edit - Session from session id
HttpSessionContext sc=request.getSession().getSessionContext();
HttpSession session=sc.getSession(session_id);
Note- This method is deprecated now due to security reason.

Try sending the response to some other jsp page and see if you are able to access session variable from there. If yes then there is problem in your current jsp.
Certainly the session is getting expired somewhere for sure otherwise request.getSession() will definitely return the previously created session.

Set timeout to 0, not -1 if you want unlimited session time.

You need to set the attribute somewhere, before you can retrieve it:
session.setAttribute("mylist", list);

Related

session variable getting lost sporadically in java

I set a userId in the session object on the pageload of homepage of my application like below
HttpSession session = req.getSession();
session.setAttribute("userId", validUserId);
When user navigates to different page of the application, I fetch this userId using normal way like below and I save this userId in database later.
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
This works for almost 95 times out of 100 calls. I am able to fetch the userId and store in database, but for 5 calls, all I get is a blank userId object.
I am not able to reproduce this issue in lower environments, so its bit difficult to understand what the issue is.
I have set the automatic expiry of the pages to 20 mins by adding the property in web.xml and then using it in jsp page.
Can some one please guide as to what could be the root cause of this issue?
Found the root cause.
When i am displaying the expiry page and invalidating the session, if user clicks on back button of the browser, it was displaying the old page again and if data is submitted now, then this variable is not available as session is already invalidated previously. Need to fix back button issue.

Remove a Cookie inside the HttpSessionListener

I have a situation where I need to create a cookie when a session is created, and when the session is removed I have to remove the cookie. When a user manually ends a session I can remove the cookie in the doGet method of the logout servlet. But when the session times out I am not able to do that, so I am planning to sue the HttpSessionListener for this, but I have seen some where that we cannot do that. Is there any other way than the one mentioned here.
Really how do want to remove a cookie when you do not access to the user?!?!
The only solution is setting cookie live-time to the exact time your cookie session is(1 hour is default)
For each request you need to set the cookie with the updated time(current_timestamp+'1 hour'), it will tell browser keep the cookie for next 1 hour.
Beside the cookie, you need to check the integrity of the cookie and the session, simply track the cookie integrity with the session(maybe a hash), it helps you when a user tries to fool your server, by providing cookie A from user A by session user B.

Saving data inside user session getting shared between user

i am having one jsp file with the following code
String name=request.getParameter("user");
if(name==null)
name=(String)request.getSession().getAttribute("name");
else
request.getSession().setAttribute("name", name);
i assume if the page get any request with user as parameter, it will save the value to that particular user session and in case the get request is not having any 'user' parameter it will try to read the user value from the session. The code is working perfectly when i host it from my local server(glassfish).
But when i upload it into some remote host, things are getting weird.
When i hit the page with parameter 'user', its saving the value in the session. But then again if i hit the page from some other browser(or after clearing cookie), its retrieving the previous value saved, instead of returning null
Am i doing something wrong, actually im pretty new to Java EE.
You cannot get previous value saved unless
1) Your session is not finished and same session is getting extended. Can you explain how you are clearing the cookies.
2) Are you typing the URL or trying to refresh the page after deleting the cookies.

Why Isn't Session Null

I am using the following code to delivery the user to a Welcome page if they are already logged in, or back to the login page if they are not.
HttpSession session = request.getSession(false);
if(session == null){
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}else{
//User already logged in. Send to home.
response.sendRedirect("Welcome");
}
First time around, it works fine, but if I reload the page even once it sends the user to the welcome page and inevitably sends me back a 500 error because there are elements on that page that cannot be loaded because the user log in code has not been executed.
Does a session get started automatically even if request.getSession(true) is not declared when a page is reloaded? Is there a way to prevent this?
Probably the session is being created upon forwarding to login.jsp. That's necessary because the user has to be assigned to an unauthenticated request and then authenticate it. If you want to redirect based on whether the user is logged in or not, use SessionContext's getCallerPrincipal.
For more info, check this (somewhat old, but still relevant) article
The method request.getSession(false) returns null if there is no current session. I suggest to compare a key too.
Please take a look at this threads.
Do JSPs always create a session?
How do servlets work? Instantiation, session variables and multithreading

Get session by id in ajax call

Is there a way to have access to session in a AJAX call made to a JAVA server.
On the server, the request object has both the session and cookies properties NULL.
I can pass though the session id as a parameter, but how can I access the session by ID?
Edit
Using session.getSession(false); returns null, while session.getSession(true); obviously returns a new session, with another id.
The best way to deal with this is to append ";jsessionid=" at the end of the url. For instance, in a jsp:
<script type="text/javascript">
...
xhr.open("GET", url + ";jsessionid=<%=pageContext.getSession().getId()%>");
...
</script>
The line:
xhr.open("GET", url + ";jsessionid=<%=pageContext.getSession().getId()%>");
is rendered as:
xhr.open("GET", url + ";jsessionid=6EBA4F94838796DC6D653DCA1DD06373");
It sounds like you don't have a session!
Make sure when the load containing the AJAX script, the session is created on the server.
session.getSession(true);
If this is stored as a cookie, then your AJAX call will submit it back to the server when it fires.
In order to access the session you do not need the session id. This is all done for you behind the scenes by your servlet container. To get the session for a particluar request all you need to do is:
HttpSession session = request.getSession(false);
where request is your HttpServletRequest. The false arg means "do not create session if it does not exist". Of course use "true" if you want the session to be created if it doesn't exist.

Categories

Resources