网页计数器 JavaBean 的设计与使用

网页计数器 JavaBean 的设计与使用

【描述】设计一个 JavaBean 记载网页的访问数量,在动态页面中访问该 JavaBean,实现网页的计数。假设要统计两个网页总共访问量。

【分析】该问题需要统计网页访问次数,在JavaBean中技术属性。在网页被访问时,该计数器自动加1,同时要存放该数值。所以,在被访问页面需要创建 application 范围的一个 JavaBean 对象。

           为了体现不同页面对 application 范围的 JavaBean 对象的共享,这里设计两个页面程序 counter1.jsp 和 counter2.jsp。

【设计】 该问题,需要3个组件(一个 JavaBean,两个JSP),即:

(1)具有统计功能的 JavaBean。

(2)获取 JavaBean 中的计数属性的值并显示结果的 JSP 页面:counter1.jsp 和 counter2.jsp。

【实现】

(1)设计记载网页访问数量的 JavaBean :Counter.java。

package beans;
public class Counter{
		private int count;
		public Counter(){count = 0;}
		public int getCount(){
			count++;
			return count;
		}
		public void setCount(int count){this.count = count;}
}

(2)第1个需要计数的网页(counter1.jsp)中访问 JavaBean 对象。

<%@ page contentType="text/html" pageEncoding="UTF-8"%>

<html>
  <head><title>网页访问数量</title></head>
  <body>
  	<jsp:useBean id="counter" scope="application" class="beans.Counter"/>
  	这次访问的是第1个页面:counter1.jsp!<br>
  	两页面共被访问次数:
  	<jsp:getProperty name="counter" property="count"/>
  </body>
</html>

(3)第2个需要计数的网页(counter2.jsp)中访问 JavaBean 对象。

<%@ page contentType="text/html" pageEncoding="UTF-8"%>

<html>
  <head><title>网页访问数量</title></head>
  <body>
  	<jsp:useBean id="counter" scope="application" class="beans.Counter"/>
  	这次访问的是第2个页面:counter2.jsp!<br>
  	两页面共被访问次数:
  	<jsp:getProperty name="counter" property="count"/>
  </body>
</html>

运行截图:

猜你喜欢

转载自blog.csdn.net/qq_40956679/article/details/83117487