package cs320.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/RequestCounter", loadOnStartup = 1) public class RequestCounter extends HttpServlet { private static final long serialVersionUID = 1L; public RequestCounter() { super(); } public void init( ServletConfig config ) throws ServletException { // When you override init(), don't forget to call the super class // init() first. super.init( config ); // Note that Java automatically converts between int and Integer // (i.e. the "Autoboxing and Unboxing" feature since JDK 1.5. int counter = 0; getServletContext().setAttribute( "counter", counter ); } protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { ServletContext servletContext = getServletContext(); // get the counter Integer counter = (Integer) servletContext.getAttribute( "counter" ); // increment the counter ++counter; // save it back the application scope servletContext.setAttribute( "counter", counter ); // display the message "the counter is incremented" PrintWriter out = response.getWriter(); response.setContentType( "text/html" ); out.println( "
The counter is incremented.
" ); out.println( "" ); } }