tags:

views:

151

answers:

2

I want to add a hit counter to my JSF web app. Like in PHP we can use an external text file to store the count and increment and write it on every request. How to use in JSF?

A: 

You could do this, but the only situation that I can think for it would be for homework. Anyway, just have a Backing Bean that reads/increments/writes the file.

Look at Apache Commons IO FileUtils for some good helper methods. Although if this is homework you will no doubt get better marks for rolling your own ;-)

Damo
A: 

I would suggest to just use a Filter for this. Implement javax.servlet.Filter accordingly and map this in web.xml on an url-pattern of interest.

E.g. (semi pseudo):

public void doFilter(request, response) {
    int count = readCountFromFile();
    count++;
    writeCountToFile(count);
    chain.doFilter(request, response);
}

The Java IO tutorial may be of help how to read and write file contents.

You don't necessarily need JSF for this. JSF is just built on top of Servlet API and you can use Filters as good with it. Otherwise you have to create a bean and you have to remember to ensure that every view calls this bean somehow on every request.

BalusC