Java Reference
In-Depth Information
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.
LISTING 21.7
The Full Text of counter.jsp
1: <%@ page import=”counter.*” %>
2: <html>
3: <head>
4: <title>Counter Example</title>
5: </head>
6: <body>
7: <h1>JSP Stats</h1>
8: <%! Counter visits; %>
9: <%! int count; %>
10:
11: <%
12: visits = new Counter(application.getRealPath(“counter.dat”));
13: count = visits.getCount() + 1;
14: %>
15:
16: <p>This page has been loaded <%= count %> times.
17:
18: <% visits.setCount(count); %>
19: </body>
20: </html>
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.
LISTING 21.8
The Full Text of Counter.java
1: package counter;
2:
3: import java.io.*;
4: import java.util.*;
5:
6: public class Counter {
7: private int count;
8: private String filepath;
9:
10: public Counter(String inFilepath) {
11: count = 0;
12: filepath = inFilepath;
21
 
Search WWH ::




Custom Search