Servlet Simple Counter : Counter « Servlet « Java Tutorial






import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  int count = 0;

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    count++;
    out.println("Since loading, this servlet has been accessed " +
                count + " times.");
  }
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletSimpleCounter.zip( 88 k)








25.6.Counter
25.6.1.Servlet Static Field As Counter
25.6.2.Servlet Simple Counter