You need to get a clearer picture of how a JSP is handled by the Engine.
JSP's get translated into a Servlet, and the code goes into the Servlet's
'service' method.
When you use <% <type> a; %> you create a local variable to the scope of the
'service' method of the resultant Servlet. If you want a variable with scope
outside the 'service' method, use: <%! <type> a; %>
Note the '!', this tells the JSP compiler that the enclosed code should be
declared at the class level of the JSP.
Same thing to define a method: <%! <type> <name>() {...} %>. These methods
will then be able to access the member variables. However, you have a very
serious danger here. Remember that a Servlet/JSP is not thread safe, so, if
two requests come in for that JSP, there is a danger of trampling on your
'global' variables.
A better solution to this is to use a model-view-controller (MVC)
architecture like Struts with view helpers.
"Paul Lee" <pa**@paullee.com> wrote in message
news:cf**************************@posting.google.c om...
Dear all,
I've written a jsp which is very large and monolithic, and what I want
to do is refactor it to provide functions that can operate on global
jsp variables.
For instance, what I have at the moment, in pseudo code is:
MyJsp.jsp
<% a = some code
b = more code %>
//perform operations on a and b
But what I really want is something like:
MyJsp.jsp
<% a = some code
b = more code %>
<!-- HTML here -->
<!-- function here -->
<%public void MyFunc()
{
// operations on a and b here
}
%>
but when I do this latter approach, I get a "token not found",
referring to a missing ;, +, ++ etc. in my code, and relating to my
defined function. People have suggested using a class declaration
within the jsp that contains the functions, or maybe using a bean, but
it seems slightly problematic to use global jsp references when doing
it this way.
Cheers
Paul