Jsp + JavaBean循序渐进教程(三)-JSP教程,Jsp/Servlet
4159 点击·0 回帖
![]() | ![]() | |
![]() | jsp和javabean结合的简单例子 上面讲了这么多,到目前还没有看到具体应用,那好,目前我们看看具体的javaserver pages+javabean的例子吧,首先让我们看看一个简单的计数器程式。 本例程共包含3个文件 javabean--counter.java文件,javaserver page-- counter.jsp文件, counter1.jsp文件其中,counter.java主要用来进行计数器的计数操作,counter.jsp和counter1.jsp文件主要用来显示网页的计数。 counter.java文件 package count; /** * title: test * description: counter bean * @author liuyufeng * @version 1.0 */ public class counter { //初始化javabean的成员变量 int count = 0; // class构造器 public counter() { } // 属性count的get方法 public int getcount() { //计数操作,每一次请求都进行计数器加一 count++; return this.count; } //属性count的set方法 public void setcount(int count) { this.count = count; } } counter.jsp文件 <html> <head> <title> counter </title> </head> <body> <h1> jbuilder generated jsp </h1> <!-初始化counter这个bean,实例为bean0--> <jsp:usebean id="bean0" scope="application" class="count.counter" /> <% //显示当前的属性count的值,也就是计数器的值,这里我们使用out.println方法,下面的counter1.jsp将使用另一种方法 out.println("the counter is : " + bean0.getcount() + "<br>"); %> </body> </html> counter1.jsp文件 <html> <head> <title> counter </title> </head> <body> <h1> jbuilder generated jsp </h1> <!-初始化counter这个bean,实例为bean0--> <jsp:usebean id="bean0" scope="application" class="count.counter" /> <!-使用jsp:getproperty 标签得到count属性的值,也就是计数器的值--> the counter is : <jsp:getproperty name="bean0" property="count" /><br> </body> </html> 从这个例子我们不难看出jsp和javabean应用的一般操作方法,首先在jsp页面中要声明并初始化javabean,这个javabean有一个唯一的id标志,更有一个生存范围scope(设置为application是为了实现多个用户共享一个计数器的功能,如果要实现单个用户的计数功能,能修改scope为session),最后还要制定javabean的class来源count.counter: <jsp:usebean id="bean0" scope="application" class="count.counter" /> 接着我们就能使用javabean提供的public方法或直接使用<jsp:getproperty>标签来得到javabean中属性的值: out.println("the counter is : " + bean0.getcount() + "<br>"); 或 <jsp:getproperty name="bean0" property="count" /> ok,目前运行一下程式看看,然后多刷新几次,注意看计数器的变化。上面的程式在jbuilder4.0下面调试通过。 如果要直接在一些jsp环境(如tomcat、ias、weblogic等)下调试,请注意各自的文件,正确的放置javabean文件。如在tomcat环境中,本例子javabean编译后的文件就需要放在<server root>web-infclasses count counter.class。 | |
![]() | ![]() |