Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Global variable

 
aakash bhatt
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
If i declare a variable as global in jsp like
<%
! int i = 0;
%>
<%
i++;
%>
At the first time it displays 1 while I click on refresh button of
my browser it displays 2 how does it gets stored like a session though
i am refreshing the page.

Regards,
aakash
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64632
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It isn't stored in the session. When you use the <%! notation, the declaration is made at the top level of the JSP-generated servlet. Therefore, your variable i becomes an instance variable of the servlet.
Since the container re-uses the servlet instance once it has been created (usually by the first hit to the JSP page), you are seeing the variable incremented every time you run the page.
The very best way to figure out why JSP pages act the way they do is to take a gander at the Java code that is generated for the page by the container.
hth,
bear
 
saikrishna cinux
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bear Bibeault:
It isn't stored in the session. When you use the <%! notation, the declaration is made at the top level of the JSP-generated servlet. Therefore, your variable i becomes an instance variable of the servlet.

Since the container re-uses the servlet instance once it has been created (usually by the first hit to the JSP page), you are seeing the variable incremented every time you run the page.

The very best way to figure out why JSP pages act the way they do is to take a gander at the Java code that is generated for the page by the container.

hth,
bear


but here i dont want to increment the i value each time i refresh my page,i want to alwayS initialize it to 0 in the declaration tag
please give me suggestion
cinux
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64632
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Easy. Don't use a declaration scriptlet.
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
which is to remove your exclamation mark. The following code makes it a local variable as opposed to instance variable.


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic