/**A Hit Counter Servlet that logs the number of non unique page hits to disk and * displays the result in HTML. * This is done without mixing code and HTML, i.e. code separation is used. * Internet Programming 2 - Course * @author Martin Carlsson */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import mixer.*; public class HitCounterHTML extends HttpServlet { private static int count = 0; private static String servletRoot = "/hit-counter-html"; private static String htmlFile = null; private String countFile = "countFile.txt"; private String htmlFileName ="hit-counts.htm"; public void init()throws ServletException { BufferedReader bR = null; countFile = getServletContext().getRealPath(servletRoot + "\\" + countFile); if(htmlFile == null) { htmlFile = Mixer.getContent(new File(getServletContext().getRealPath(servletRoot + "\\" + htmlFileName))); } try { bR = new BufferedReader(new FileReader(countFile)); String countString = bR.readLine(); count = Integer.parseInt(countString); return; } catch (FileNotFoundException fNfE){ System.err.println("Couldn't find file " + countFile); } catch (IOException iOe){ System.err.println("Couldn't read file " + countFile); } catch (NumberFormatException nFe){ System.err.println("Value not valid in file " + countFile); } finally{ try{ if(bR !=null) bR.close(); } catch(IOException iOe){ System.err.println("Could not close BufferedReader stream"); } } } /*Saves the number of clients requesting this servlet every 10 request.*/ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { Mixer m = new Mixer(htmlFile); //res.setContentType("text/plain"); PrintWriter out = res.getWriter(); int localCount; synchronized(this){ localCount = ++count; if(localCount % 10 == 0)//sparar till disk var 10:e sidbesök saveCount(); } m.add("_m_", "Total number of hits: " + localCount); res.setContentType("text/html"); out.println(m.getMix()); } /*Is called when the servlet unloads. Calls the destroy() method of the super class, then savestate()*/ public void destroy() { saveCount(); } //Saves to disk public void saveCount() { PrintWriter pW = null; try { pW = new PrintWriter(new FileWriter(countFile)); pW.println(count); return; } catch(IOException IoE){ System.err.println("Couln't write to " + countFile); } finally{ if(pW != null) { pW.close(); } } } } // End class HitCounterHTML