We left out one major item from the last topic - structuring your code using procedures or since we are working with Java - methods. To create and use methods in a JSP we need to use what are known as JSP Declarations.
<%! declarations %>
A declaration can consist of either methods or variables, static constants are a good example of what to put in a declaration.
You can use declarations to declare one or more variables at the class level of the compiled servlet. The fact that they are declared at class level rather than in the body of the page is significant. See notes on Class Variable Scope below. The methods can then be used by Java code in the rest of the page.
In the following example we are declaring both a variable and a method. Within the body we make use of the method to add the two numbers 10 and 12.
<head>
<%!
private static int PI = 3.1415;
private int addNumbers(int a, int b)
{
return a + b;
}
%>
</head>
<body>
<p>10 plus 12 is <%= addNumbers(10, 12) %></p>
<p>A circle of width 10cm has <%= PI * 10 %> cm
circumference.</p>
</body>
The scope of variables declared in the declarations section is important. The JSP page is compiled once to a servlet and then that servlet is accessed by the web server. Now because these variables are being declared at the class level then they aren't instantiated for each new JSP page request, that is, they have application scope for that page. Click the icon below to view a demo illustrating this.
The following workshop looks at using JSP declarations.