Let’s develop the application.
PageVisitors.java
|
package
in.ap.nlg.rjp.bgl;
import
java.io.IOException;
import
java.io.PrintWriter;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
/**
*
* @author Sreekanth Goud G.
* @since 22-April-2012
*/
public
class PageVisitors extends HttpServlet {
private static long pageVisits = 0;
/**
* Processes requests for both HTTP
<code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a
servlet-specific error occurs
* @throws IOException if an I/O error
occurs
*/
@Override
public void service(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {
synchronized(this) {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet
PageVisitors</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Page visitor: " + pageVisits +
"</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
/**
* Handles the HTTP
<code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a
servlet-specific error occurs
* @throws IOException if an I/O error
occurs
*/
@Override
protected void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
/**
* Handles the HTTP
<code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a
servlet-specific error occurs
* @throws IOException if an I/O error
occurs
*/
@Override
protected void doPost(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
}
|
web.xml
|
<?xml
version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>PageVisitors</servlet-name>
<servlet-class>in.ap.nlg.rjp.bgl.PageVisitors</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PageVisitors</servlet-name>
<url-pattern>/pageVisitors</url-pattern>
</servlet-mapping>
</web-app>
|
|
Directory Structure
|
Out put
|
|
|
|
synchronized block plays the key role here, in general, service method will be executed with respect to each request as a Thread. There is a change to get more than one request at a time. In such cases, if your not using this synchronized block, then, at the same time both requests will be processed with the same pageVisits value.
So, you'll not get the unique count. This is avoided by using synchronized block. Since, this block will allow, only one Thread at a time.

