我写在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;
    }
} 
有帮助吗?

解决方案

更改这部分代码:

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

希望这有助于。

更新:顺便说一句,这是更好地选择适合您的计数器类的方法更好的名称。首先,改变setCounsetCount。此外,setter方法通常只分配传递给它到其关联字段的值。如果你想增加coun的价值,方法名称更改为addCount。然后递增像count值:

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

其他提示

 <%@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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top