JSP variable scope issue

K

Ken

I have a page of the form:

== Start ==

<%! int someVariable = 0; %>
<%= someVariable %>
<% someVaribale++; %>

== End ==
Now when I run the page the first time I get 0 then each subsequent
time a higher number... Why? I should think the scope of someVariable
is local and to make the scope application or session I would need to
do something special. I even clear the cache on firefox and the bloody
thing still increments.

I'm using Netbeans 6.7.1 with Glassfish v3 if it makes a difference.
 
L

Lew

Ken said:
I have a page of the form:

== Start ==

<%! int someVariable = 0; %>
<%= someVariable %>
<% someVaribale++; %>

== End ==
Now when I run the page the first time I get 0 then each subsequent
time a higher number... Why? I should think the scope of someVariable
is local and to make the scope application or session I would need to
do something special. I even clear the cache on firefox and the bloody
thing still increments.

"<%!" opens a declaration block, so 'someVariable' is an instance variable of
the servlet. Servlet containers like to reuse servlet instances whenever
feasible and permitted. So you have the same instance with the same member
incrementing.

Don't use scriptlet in JSP.
 
D

Daniel Pitts

Ken said:
I have a page of the form:

== Start ==

<%! int someVariable = 0; %>
<%= someVariable %>
<% someVaribale++; %>

== End ==
Now when I run the page the first time I get 0 then each subsequent
time a higher number... Why? I should think the scope of someVariable
is local and to make the scope application or session I would need to
do something special. I even clear the cache on firefox and the bloody
thing still increments.

I'm using Netbeans 6.7.1 with Glassfish v3 if it makes a difference.
"<%!" starts a class-level declaration. so someVariable is declared at
the JSP servlet object level. you could use <% int someVariable = 0;
%>. The better alternative is to not use scriptlets at all, and use
some form of MVC architecture.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top