views:

90

answers:

2

Can the object of type HttpSession called session be accessed from a function?

In a simple jsp page I have a function(see below) defined in the header of the page, and set to an onclick handle of for a button. When I press this button, I'll never see the second alert message. If I do something in the body of the page (like Session ID: <%= session.getId() %> ) I have no trouble accessing it. What newbie mistake am I making?

     function doTest()
 {
  alert('Preforming test 122333232');

      String sessionId = session.getId();

      alert('After access');

      if(sessionId == null)
      {
        alert('session id is null?');
      }

Thanks

A: 

I may be totally missing what you're doing here, but the function you've provided looks like javascript. If that is the case, then you should change it to:

var sessionId = "<%= session.getId() %>";

The generated JSP code will output HTML with your javascript function intact, but it will replace that JSP expression with the session id.

Shaun
Yes it is javascript but when I try what you suggest I get a compile error when I test the page.
I had to remove the ; after the getId() call. I.e. var sessionId = "<%= session.getId(); %>";
Sorry about that, I should've noticed that extra semicolon. Fixed it in my response now.
Shaun
A: 

You're confusing/mixing Java/JSP with Javascript. Those are entirely distinct languages, each running in its own environment. Java/JSP runs at the server machine, produces HTML/CSS/JS output, sends it as HTTP response to the client machine. When the client machine retrieves the response, it starts to parse/interpret/execute HTML/CSS/JS. Java/JSP doesn't run at the client machine. Javascript doesn't run at the server machine.

To access any Java variables in Javascript you need to let JSP print it as if it is a Javascript variable:

var sessionId = '${pageContext.session.id}';

If you request this JSP page, then it will produce something like the following in the HTML/CSS/JS output (rightclick page in browser and choose View Source to see it yourself):

var sessionId = 'F876B130590427C4E35DDE2C7CC0EB3D';

This way JS can use it further while running at client machine.

To learn more about the wall between Java/JSP and Javascript you may find this article useful as well: http://balusc.blogspot.com/2009/05/javajspjsf-and-javascript.html

Note that I don't recommend to use scriptlets (the <% %> things) for this. Its use is discouraged since a decade and they are considered bad practice nowadays.

BalusC

related questions