Java Tutorial - Java Script : Using Declarations:

Java Tutorial - Java Script :

Using Declarations:

Another element you can insert into a JSP page is a declaration, which is a statement that sets up a variable or method that will be defined in the page when it’s compiled into a servlet. This feature is primarily used in conjunction with expressions and servlets. Declarations are surrounded by <%! and %> tags, as in the following example:
<!% boolean noCookie = true %>
<!% String userName = “New user” %>
These declarations create two instance variables: noCookie and userName. When the JSP page is compiled into a servlet, these variables will be part of the definition of that class. Listing 21.7 contains a page that uses a declaration to present a counter.
Before you can try this page, you need to create a helper class that’s called by statements in lines 8, 12, 13, and 18 of the page. The Counter class in Listing 21.8 represents a web counter that tallies each hit to a page.
After you compile this class successfully, it should be stored in a WEB-INF\classes\ counter subfolder in the same part of the webapps hierarchy as counter.jsp. For example, if the JSP page is in webapps\examples\jsp, the class file should be saved in webapps\examples\WEB-INF\classes\counter. The Counter class loads an integer value from a file called counter.dat that is stored on the web server. The getCount() method retrieves the current value of the counter, and the setCount(int) method sets the current value. After the value is set, it’s saved to the file so that the counter continues to incrementally increase. Figure 21.7 shows counter.jsp loaded in a web browser.