Meaningless Drivel is fun!*
The moose likes JSP and the fly likes Global variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSP
Bookmark "Global variable" Watch "Global variable" New topic
Author

Global variable

aakash bhatt
Ranch Hand

Joined: Jan 09, 2003
Posts: 182
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

Joined: Jan 10, 2002
Posts: 60774
    
  65

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


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
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


A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

Easy. Don't use a declaration scriptlet.
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
which is to remove your exclamation mark. The following code makes it a local variable as opposed to instance variable.




java j2ee job interview questions with answers | Learn the core concepts and the key areas
 
 
subject: Global variable
 
Similar Threads
Conditional assignment
common xsl
Any good resources about design of XML
Blank page returned when filters are used with struts
Error Page