views:

41

answers:

1

I am writing a hit counter in JSP, for my coursework. I have write the code, and there is not error and its working, but the problem is that: if the user have open the website and try to use different page, whenever that the user goes back to the home page the counter still is adding a number, how can I restrict this part? shall restrict it with session? this is my code :

<jsp:useBean id="counter" scope="application" class="counter.CounterBean" />
The current count for the counter bean is:
<jsp:setProperty name="counter" property="coun" value="1"></jsp:setProperty>
<%
counter.saveCount();
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>

Bean:

package counter;

import java.sql.*;
import java.sql.SQLException;

public class CounterBean implements java.io.Serializable {

    int coun = 0;

    public CounterBean() {
        database.DatabaseManager.getInstance().getDatabaseConnection();
    }

    public int getCoun() {
        return this.coun;
    }

    public void setCoun(int coun) {
        this.coun += coun;
    }

    public boolean saveCount() {
        boolean _save = false;
        database.SQLUpdateStatement sqlupdate = new database.SQLUpdateStatement("counter", "hitcounter");
        sqlupdate.addColumn("hitcounter", getCoun());
        if (sqlupdate.Execute()) {
            _save = true;
        }
        return _save;
    }

    public int getVisitorsNumber() throws SQLException {
        int numberOfVisitors = 0;
        if (database.DatabaseManager.getInstance().connectionOK()) {
            database.SQLSelectStatement sqlselect = new database.SQLSelectStatement("counter", "hitcounter", "0");
            ResultSet _userExist = sqlselect.executeWithNoCondition();
            if (_userExist.next()) {
                numberOfVisitors = _userExist.getInt("hitcounter");                
            }
        }
        return numberOfVisitors;
    }
} 
+2  A: 

Change this part of the code:

<%
counter.saveCount();
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>

To

<%
if (session.isNew()) {
    counter.saveCount();
} else {
    counter.setCoun(-1);
}
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>

Hope this helps.

UPDATE: By the way, it's better to choose better names for the methods of your Counter class. First of all, change setCoun to setCount. Besides, a setter method usually just assigns the value passed to it to its associated field. If you want to increment the value of coun, change the method name to addCount. Then increment the count value like:

<jsp:setProperty name="counter" property="coun" value="${1 + counter.coun}"></jsp:setProperty>
Bytecode Ninja
thank you o much its working
thanks for ur advise Bless you
You're welcome. :) And good luck with your assignments. :)
Bytecode Ninja