aspose file tools*
The moose likes Servlets and the fly likes displaying the number of times a page has ever been accessed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "displaying the number of times a page has ever been accessed" Watch "displaying the number of times a page has ever been accessed" New topic
Author

displaying the number of times a page has ever been accessed

April Benzine
Greenhorn

Joined: Sep 23, 2004
Posts: 17
Hi all,
I can't figure out how do the code for displaying how many times my page has ever been accessed. here is my code I have so far. historyNum is an instance variable.

public synchronized void writeNumToFile() {
historyNum ++;
try {
in = new BufferedReader(new FileReader("c:\\projects\\src\\java146\\project3\\visitHistory.dat"));
} catch (FileNotFoundException fnfe) {
System.out.println("File not found.");
fnfe.printStackTrace();
} catch (IOException fnfe) {
System.out.println("Cannot read file.");
fnfe.printStackTrace();
}


}


Thank you!!
April Benzine
Greenhorn

Joined: Sep 23, 2004
Posts: 17
I don't think I explained this very well.
suedocode:
-use file to store number
-init method
-open history file and read data (just contains a number)
-private int historyNum
-public synchronized void writeNumToFile(){
-increment
-open file
-write to file
-close file
}
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30537
    
150

April,
A BufferedReader is for reading. You need to use a BufferedWriter to write out the result. Note that doing the file I/O inside a synchronized block is slowing the number of hits to the servlets and not recommended.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
better use a memory cache for the number and update the file only during server shutdown. You may elect to have a separate thread update the file more often (say once an hour) to prevent data loss in case the server goes down without writing the file (read: server crashes).

That way your code will perform a lot better.
Not making it synchronised may mean your count may be a bit low during heavy traffic as maybe a few updates are missed but that's almost certainly worth the price.


42
Fisher Daniel
Ranch Hand

Joined: Sep 14, 2001
Posts: 582
Hi April,
I think it is better that our servlet doesn't access a directory in a computer. Because if your application is moved to another computer, you have to change the directory.

I agree with Jeroan Wenting, and you can then save the number into database when the server is shutdown.

Correct me if I am wrong
Hope this helps
daniel
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: displaying the number of times a page has ever been accessed