01 package interval;
02
03 import java.io.*;
04 import javax.servlet.*;
05 import javax.servlet.http.*;
06
07 public class PersistentCounter extends HttpServlet {
08
09 private SaveServletStats stats;
10 private String filename;
11
12 class SaveServletStats implements Serializable {
13 public int calledCount = 0;
14 }
15
16 public void init(ServletConfig config) throws ServletException {
17 super.init(config);
18 filename = config.getInitParameter("filename");
19 stats = new SaveServletStats();
20 if (filename != null) {
21 try { ObjectInputStream in = new ObjectInputStream( new FileInputStream(filename + ".ser"));
22 stats = (SaveServletStats) in.readObject();
23 in.close(); }
24 catch (Exception e) { e.printStackTrace(); }
25 }
26 }
27
28 public void doGet(HttpServletRequest req, HttpServletResponse res)
29 throws ServletException, IOException {
30 res.setContentType("TEXT/HTML");
31 PrintWriter out = res.getWriter();
32 out.println("<HTML><TITLE>PersistentCounter</TITLE><BODY>");
33 stats.calledCount++;
34 out.println("<H4>This servlet has been called: </H4><BR>");
35 out.println("<B>" + stats.calledCount + "</B> times since the servlet was loaded ALL servlet life-cycle sessions<BR>");
36 synchronized (this) {
37 if (filename != null) {
38 ObjectOutputStream outstats = new ObjectOutputStream( new FileOutputStream(filename + ".ser"));
39 outstats.writeObject(stats);
40 out.println("Saving stats file: " + stats.calledCount + " times<BR>");
41 outstats.close();
42 }
43 }
44 out.println("</BODY></HTML>");
45 out.close();
46 }
47 }
|