如何限制JSP命中计数器?

时间:2010-04-18 14:48:25

标签: java jsp hitcounter

我正在JSP中编写一个计数器,用于我的课程。我已经编写了代码,并没有错误及其工作,但问题是: 如果用户打开网站并尝试使用不同的页面,只要用户返回主页,计数器仍然在添加数字,我该如何限制此部分?会议限制吗? 这是我的代码:

<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);
%>

豆:

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 个答案:

答案 0 :(得分:2)

更改此部分代码:

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

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

希望这有帮助。

更新:顺便说一下,最好为Counter类的方法选择更好的名称。首先,将setCoun更改为setCount。此外,setter方法通常只将传递给它的值赋给其相关字段。如果要增加coun的值,请将方法名称更改为addCount。然后递增count值,如:

<jsp:setProperty name="counter" property="coun" value="${1 + counter.coun}"></jsp:setProperty>

答案 1 :(得分:1)

 <%@page import="java.io.*,java.util.*" %>

 <html>
 <head>
 <title>Applcation object in JSP</title>
 </head>
 <body>
 <%


Integer hitsCount=(Integer)application.getAttribute("hitcount");
int m;
       if(hitsCount==null)
   {

            m=1;

      hitsCount =Integer.valueOf(m);
                   application.setAttribute("hitcount", hitsCount);
 }
 else
     {

      hitsCount=(Integer)application.getAttribute("hitcount");
       m=hitsCount.intValue()+1;
      hitsCount=   Integer.valueOf(m);
        application.setAttribute("hitcount", hitsCount);

     }



%>


<center>
<p>Total number of visits:<%=hitsCount.intValue()%> </p>
</center>
</body>
</html>