Rueda P wrote:

> I have tried declaring counter using <%! %> .
>
> What I found is that when this jsp, containing the counter, is accessed,
> counter increment.
>
> So, my assumption is that the variable declared withing <%! %> is
> declared as static global variable.
>

You might want to look at the JSP Specification, available at:

    http://java.sun.com/products/jsp/download.html

for a definitive description of what these directives mean, and what they do.

>
> Is this correct????
>

No, but it amounts to almost the same thing in a JSP environment.

Consider a JSP page with these contents (among other things):

    <%! int a = 0; %>
    <% int b = 0; %>

If you look at the source code of the servlet that is generated for this page, you
will find the following:

    public class xxxxx extends yyyyy {

        int a = 0;

        public void _jspService(ServletRequest request,
            ServletResponse response) throws ServletException, IOException {

            int b = 0;

        }

    }

In other words, a variable declared inside "<%! %>" becomes an *instance* variable
in the generated servlet class, while the "<% %>" variable becomes a *local*
variable inside the servlet's service method.

So what's the difference?  The "a" variable is shared among all users of this
particular page, so modifications made to it are visible to everyone.  The "b"
variable is reinitialized on each request, and it is not shared between requests --
each simultaneous request is running on a separate thread, with a separate stack
that contains all of the local variables.

How is an instance variable different from a static variable?  Well, there is one
copy of an *instance* variable for each *instance* of the enclosing class, while
with statics there is a single copy of the variable for an entire class loader (for
servlets and JSPs, that really means for an entire web application).

The reason that instance variables and static variables have almost the same effect
in JSPs and servlets is that the servlet container guarantees that there will be
only one instance of the class (unless you implement SingleThreadModel, but that's
a different discussion).  Since all users share the same instance of the JSP page,
there is little practical difference between statics and instance variables in JSP
pages and servlets.  However, they are substantially different in general Java
programming, where you might have many instances of a particular class.

>
> Rueda
>

Craig McClanahan

===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
For digest: mailto [EMAIL PROTECTED] with body: "set JSP-INTEREST DIGEST".
Some relevant FAQs on JSP/Servlets can be found at:

 http://java.sun.com/products/jsp/faq.html
 http://www.esperanto.org.nz/jsp/jspfaq.html
 http://www.jguru.com/jguru/faq/faqpage.jsp?name=JSP
 http://www.jguru.com/jguru/faq/faqpage.jsp?name=Servlets

Reply via email to