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 javax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet {
private int calledCount;
public void init(ServletConfig config) throws ServletException {
calledCount = 0;
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("<H2>Servlet API Example - SimpleCounter</H2><HR>");
out.println("<H4>This servlet has been called: " + calledCount +
" times.</H4>");
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.


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


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.
Simple counter servlet Reviewed by 1000sourcecodes on 22:21 Rating: 5
Powered by Blogger.