import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

// This simple class demonstrates how data can be communicated
// between separate threads using context and configuaration objects.

public class counter extends HttpServlet 
                     implements SingleThreadModel {


  // To be able to access the configuaration outside of init, we
  // store it as a state variable.

  ServletConfig storedConfig;

  // init is called when the web container calls the servlet for
  // the first time. Here, we use it to read an initial count from
  // the web.xml container and store it as a shared resource. 

  public void init(ServletConfig config) {

    // Get the value corresponding to the initial count from the
    // web.xml file. 

    String initCount = config.getInitParameter("InitialCount");

    // We then store that name value pair as an attibute in the
    // servlet context, which in turn is part of the overall 
    // servlet configuration. We then store the configuration
    // in the state variable.

    ServletContext context = config.getServletContext(); 
    context.setAttribute("count", initCount);
    storedConfig = config;
    } 

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
              throws ServletException, IOException {
  
    // When a request is posted to the servlet, we retrieve the current
    // context from the stored configuaration state variable, and then
    // retrieve the count from that context.

    ServletContext context = storedConfig.getServletContext();
    int count = Integer.parseInt((String)context.getAttribute("count"));

    // We then increment the count, and store it back into the context
    // which is still stored in the configuration.    

    count = count + 1;
    context.setAttribute("count", ""+count);
    PrintWriter out = response.getWriter();

    // Finally, we write the count into a web page to send as the response.

    out.println("<HTML><BODY><P>Your ID number is <B>");
    out.println("" + count + "</B>.");
    out.println("</P></BODY></HTML>");     
    }

  }


