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.
Related
I'm stuck with a problem:
i have an array of object in vuejs
TablePlayers[]
this.TablePlayers.push({'message': this.returnmsg, 'player': true, 'Time': time});
i send it to my java controller with:
axios.get("http://localhost:8080/SetTablePlayers/"+this.TablePlayers)
then i add this table of object to java session with :
HttpSession session = request.getSession();
session.setAttribute("TablePlayers", TablePlayers);
3.and when i would get this object from session :
TablePlayers= (List<Players>)session.getAttribute("TablePlayers");
it returns null.
how can i fix that thanks, and this is right?
You cannot send your JSON data that way. Please use an http POST method and send the data into the body of the request.
axios.post("http://localhost:8080/SetTablePlayers/", this.TablePlayers)
of course you have to adapt also your server code.
GET method should be used to obtain something from the server instead.
I have a legacy Java 1.6 running localhost with Tomcat 7 application using JSP pages, a frameset with frames, javascript, but no framework like Struts. I pass an object to display in the page from the servlet using the request or session and that works fine.
However, I made some changes recently and now I can't retrieve that same object back from the session or request. It had been working fine previously, so I'm not sure what is broken, but I can't even send a string value back from the JSP's back to the servlet.
I created a new stripped down JSP and I can't get anything back from that either using the request or session. It does the same thing when I push the code our Tomcat 6 web server. Using the debugger, I see the objects populated in the session, but then lost later when a new session is created each time as in using this simple code to get the sessionid:
System.out.println("The session id is: " + session.getId());
The session id is: EB431C19B41957B2BB2EFC3DBAF32241
The session id is: C9CBD30E84D5C93DF6114C1412AE5523
I then see this in firebug under the Header, response headers:
Set-Cookie JSESSIONID=C9CBD30E84D5C93DF6114C1412AE5523; Path=/Name omitted here/; HttpOnly,
so I know cookies are set. I also removed jquery and I"m stripping down the jsp code as much as possible, but that doesn't seem to be the issue.
I'm using:
HttpSession session = request.getSession(true); but using false didn't matter.
session.setAttribute("ObjNameList", objNameList);
The context.xml has cookies set to true and we do use response.sendRedirect, but only if an error is thrown as in: response.sendRedirect("Error.jsp"); There is no place in the code with session invalidate either.
All I'm doing from the jsp is sending a form back using something like:
document.formName.submit(); which works fine. Using this code to try and set a simple string in the session doesn't work either:
session.setAttribute("somevalue","someValue");
Gives me null in the servlet here:
String val = (String) session.getAttribute("somevalue");
Any ideas as to what could be causing this?
Resultion:
It turned out to be an issue with the url, a typo actually, as BalusC mentioned, so the path for the session cookies didn't match between the jsp and the servlet.
Doublecheck if the request URL to that servlet matches the session cookie domain and path. If it doesn't match, then the browser simply won't send the session cookie back along with the request and the server will think that there's no means of an established session and will therefore simply create a new one.
You can check cookies in the HTTP traffic monitor of browser's web developer toolset (press F12 in Chrome/Firefox23+/IE9+ and open "Network" tab). When a new session starts, the server must have returned a response with Set-Cookie header with therein the cookie value and path (and implicitly domain). When the browser sends a subsequent request on the same domain and path, then it must have passed that cookie back via Cookie request header.
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
I am creating a Login Application in JAVA.I am making the presentation in JSP and all the logic (Database connectivity) in Servlet [this is not a right approach I know that].
I check the username Password in Servlet and then create a session variable.
and add the session like this
sess.setAttribute("username",oName);
Then I redirect the user to its homepage say student.jsp
response.sendRedirect("student.jsp");
It removes the session variable.I need a way to preserve the session variable and move to student.jsp.I tried to use forwading but that didn't worked out.
RequestDispatcher dispatcher =
getServletContext()
.getRequestDispatcher("/student.jsp");
if (dispatcher != null) {
dispatcher.forward(request, response);
}
It forward request but the Page address doesn't change to student.jsp which is not good.
Any help in this regard will be appreciated
Thank you
For the redirected request to come back and attach to the same session, it needs a session ID, usually carried in a JSESSIONID (or another name) cookie or in the URL as a parameter.
This cookie or URL parameter should be added by the servlet container and you should not have to add it yourself.
If you do not see the cookie in your browser, and you are not attaching the JSESSIONID to the URL, then it is creating a new session with each request, and not attaching to the same session.
Try to edit your tomcat context.xml file and replace <Context> tag to <Context useHttpOnly="false"> , this helped me.
Some browsers like Chromium for instance do not allow cookies from localhost or IP addresses, so the session cannot be preserved and changes on every refresh. This can be easily checked with the browser developer tools that show all cookies of the request.
For development, set up your workstation to resolve some more serious name (like host.kitty.com) into localhosts. Under Linux, just add entry to /etc/hosts.
Use the RequestDispatcher and set your username variable using request.setAttribute(). In this case the dispatcher will not create a new request but the same request will be forwarded using the forward() method.
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);
I understand that if we use the following statement
HttpSession session = request.getSession();
Will create the Unique session id, Create Cookie and associate Cookie with the Session id.
and helps the container to keep track and identify the clients.
Yes, My question, is there a possibility for me to see the cookie header and Unique Id created by this statement request.getSession()?
You can retrieve a HTTP Header using
HttpServletRequest.getHeader.
Although a session can be created by calling HttpServletRequest.getSession(true)
it's rather done by the webcontainer. As edl already wrote HttpServletRequest.getSession().getId() returns the session id.
You can see it using any HTTP header tracker tool. Firebug for example shows the headers in the Net panel. Here's a screenshot (click here for full size):
Any newly created cookie will appear as Set-Cookie header in the response. The client will send the same value back as Cookie header in the subsequent requests in the same session so that the server can identify the client session. For a JSP/Servlet webapplication, your interest is the cookie with the name JSESSIONID.
You can use session.getId() for the ID I believe. Not sure about the header.
I found more information in the following URL
http://www.javacertifications.net/javacert/session.jsp