Java Reference
In-Depth Information
LISTING 21.8
Continued
13: }
14:
15: public int getCount() {
16: try {
17: File countFile = new File(filepath);
18: FileReader file = new FileReader(countFile);
19: BufferedReader buff = new BufferedReader(file);
20: String current = buff.readLine();
21: count = Integer.parseInt(current);
22: buff.close();
23: } catch (IOException e) {
24: // do nothing
25: } catch (NumberFormatException nfe) {
26: // do nothing
27: }
28: return count;
29: }
30:
31: public void setCount(int newCount) {
32: count = newCount;
33: try {
34: File countFile = new File(filepath);
35: FileWriter file = new FileWriter(countFile);
36: BufferedWriter buff = new BufferedWriter(file);
37: String output = “” + newCount;
38: buff.write(output, 0, output.length());
39: buff.close();
40: } catch (IOException e) {
41: // do nothing
42: }
43: }
44: }
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 exam-
ple, 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.
 
Search WWH ::




Custom Search