一、Java Bean行文
1.重点说明
Java Bean行为是一组与Java Bean相关的行为,包括useBean行为、setProperty行为、getProperty行为等。Java Bean就是普通的Java类。Java Bean类非常简单,只有私有属性与对应的getter方法和setter方法。(注意:对于boolean类型的属性,习惯上一般把getter方法写成isXxx(),而不是getXxx())
2.代码实践
scope实现各种计数器
Counter.java
1 package com.bean; 2 3 public class Counter { 4 5 private int count; //计数器 6 7 public int getCount(){ //每访问一次,计数器自加1 8 return ++count; 9 } 10 public void setCount(int count){ 11 this.count = count; 12 } 13 } |
Counter.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'Counter.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <!-- 定义一个session范围内的计数器,记录个人访问信息 --> 27 <jsp:useBean id="personCount" class="com.bean.Counter" scope="session" /> 28 <!-- 定义一个application范围内的计数器,记录所有人的反问信息 --> 29 <jsp:useBean id="totalCount" class="com.bean.Counter" scope="application" /> 30 <div align="center"> 31 <form action="page/Counter.jsp" method="get"> 32 <fieldset style="width:300"> 33 <legend>计数器</legend> 34 <table align="center" width="400"> 35 <tr> 36 <td>您的访问次数: 37 </td> 38 <td> 39 <!-- 获取个人的访问次数 --> 40 <jsp:getProperty property="count" name="personCount"/> 41 </td> 42 </tr> 43 <tr> 44 <td>总共的访问次数: 45 </td> 46 <td> 47 <!-- 获取所有人的访问次数 --> 48 <jsp:getProperty property="count" name="totalCount"/> 49 </td> 50 </tr> 51 <tr> 52 <td colspan="2"> 53 <input type="submit" value="刷新"> 54 </td> 55 </tr> 56 </table> 57 </fieldset> 58 </form> 59 </div> 60 </body> 61 </html> |