Hit Counter Servlet - Safe File Handling

The purpose of this assignment was to:

The description and my solution of the Hit Counter Servlet with Safe File Handling -assignment can be viewed and/or downloaded at the bottom of this page.

About Safe File Handling and Synchronization

From servlet-authors perspectives, each client/browser is a thread that calls the servlet by the doGet() or doPost() method:

Servlet Request and Threads


Since a servlet get requests by many HTTP clients(browsers) simultaneously it's important that no writing to the same file or variable occur concurrently.

If a servlet only read from the request, write to the response, and save data in local variables (i.e., to variables declared within a method), there is no need to worry about the interaction among threads.

However, once any data is saved to a file or in non-local variables (i.e., saved to variables declared outside any of the class methods), it's important to understand that each of these client threads has the ability to manipulate either the file or the servlet's non-local variables.

Without precautions, this may result in data corruption and inconsistencies.

To overcome this a technique called synchronization can be used.

What does "static amount of dynamic text" mean?

It means that the amount of text will stay just about the same, but the text itself will be different.

Assignment Description

Create a servlet that implements a hit counter for the total number of times it has been requested.

The number of hits should be stored in a file on the server-side, and when requested shown to clients(browsers) with the mime-type/content-type "text/plain".

Here it is important to prevent simultaneous writing to the file stored on the server-side.

Use synchronization, but keep the amound of synchronized code to a minimum since synchronization can slow things down if used too much.

My Solution, Assignment Files

Note: This simple text-based hit counter -servlet shows the total number non-unique hits.

Try the text based Hit Counter

«  Previous Next  »
Loading