Simple counter servlet


SimpleCounter is another simple servlet, but here we have an instance counter variable that is initialized in the init method (Example 1).

Example 1
package itso.servjsp.servletapi;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet {
private int calledCount;
public void init(ServletConfig config) throws ServletException {
super.init(config);
calledCount = 0;
}
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML><BODY>");
out.println("<H2>Servlet API Example - SimpleCounter</H2><HR>");
++calledCount;
out.println("<H4>This servlet has been called: " + calledCount +
" times.</H4>");
out.println("</BODY><HTML>");
out.close();
}
}
Every time this servlet is invoked, we increment this counter variable, calledCount, by one. The first time this servlet loads, we initialize the counter to 0. Subsequent invocations keep incrementing the counter.

Persistence

This example demonstrates the persistence property of servlets, where an instance variable can remain active for the life of the servlet. Every time a servlet thread is spawned to handle the servlet request, it has access to this global instance variable. This could be useful in the case where these instance variables take a long time to initialize, such as database connections, and we want to set them once and reuse them with each invocation, without having to incur the initialization overhead each time. 

This is a commonly used technique, particularly when we are only initializing data, and then reading global variables, as is the case with database connections. In this example, however, we are reading and updating

Multi-Threaded

Because our requests to this servlet are handled in threads against the same servlet object, we must implement mechanisms to guarantee thread safety for these shared instance variables, because we can update them in separate threads. In other words, there is no guarantee that the line that increments the counter and the line that prints out the counter will be executed asynchronously within a thread. So, we must identify critical sections of code, and synchronize these sections if appropriate.
Share this article :
 
Copyright © 2012. Best Online Tutorials | Source codes | Programming Languages - All Rights Reserved