Gabriel Diaconescu
Gabriel Diaconescu

Reputation: 1799

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.

Upvotes: 3

Views: 9717

Answers (3)

Maurice Perry
Maurice Perry

Reputation: 32831

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");

Upvotes: 3

Richard H
Richard H

Reputation: 39065

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.

Upvotes: 0

npellow
npellow

Reputation: 1985

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.

Upvotes: 0

Related Questions