工作关系,需要做一个页面统计功能,具体为:当一个用户访问平台首页时,进行一次统计。具体实现为:
dwr 配置 dwr.xml
<dwr>
<allow>
<create creator="new" javascript="DWRScript">
<param name="class" value="SessionCount"></param>
</create>
</allow>
</dwr>
统计计数的页面:sessionCount.jsp
<html>
//需导入dwr,根据自己的实际路径配置
<script type="text/javascript" src="dwr/util.js"></script>
<script type="text/javascript" src="dwr/engine.js"></script>
<script type="text/javascript" src="dwr/interface/DWRScript.js"></script>
<script type="text/javascript" src="js/sessioncount.js"></script> //统计访问量的js
<script type="text/javascript"> // 页面需要加载的js
function SessionNUll() {
var sessionCount="<%=session.getAttribute("CountPerson")%>";
var Count = document.getElementById("sessionCount");
if(sessionCount=="null"){
getCountSession(Count);
}else{
Count.innerText = sessionCount;
}
}
</script>
<body οnlοad="SessionNUll();">
<div>
<span>您是第</span><span id="sessionCount" style="color:#FF0000"></span>位访问者
</div>
</body></html>
//sessioncount.js
function getCountSession(obj){
DWRScript.getCountPerson(function (data) {
obj.innerText = data;
});
}
SessionCount.java
public class SessionCount{
public String getCountPerson(){
HttpSession session = WebContextFactory.get().getSession();
int countPerson_trips = 0;
String sql = "select person_trips from sessioncount";
try {
open();
st = dbConn.createStatement();
rs = st.executeQuery(sql);
if(rs.next()){
countPerson_trips = rs.getInt(1);
st.execute("update sessioncount set person_trips = "+(++countPerson_trips));
}
session.setAttribute("CountPerson", countPerson_trips);
close();
} catch (SQLException e) {
close();
e.printStackTrace();
}
return ""+countPerson_trips;
}
}
OK,这样就可以用dwr实现页面的统计功能了