JSP JavaBeans

2018-03-20 14:17 更新

JSP教程 - JSP JavaBeans


JavaBean是遵循JavaBeans API規(guī)范的Java代碼。

JavaBean具有以下功能。

  • 它有一個(gè)默認(rèn)的無(wú)參數(shù)構(gòu)造函數(shù)。

  • 它應(yīng)該實(shí)現(xiàn) Serializable 接口。

  • 它有一個(gè)讀取或?qū)懭雽傩缘牧斜怼?/p>

  • 它有一個(gè)屬性的getter和setter方法列表。

以下代碼顯示如何創(chuàng)建學(xué)生JavaBean。

firstName,lastName和age都是屬性。每個(gè)屬性都有一個(gè)getter方法和一個(gè)setter方法。

例如,firstName的getter方法是getFirstName,它是由大寫的屬性的第一個(gè)字母和append獲取到前面創(chuàng)建的。

我們可以使用相同的方法來(lái)創(chuàng)建setter方法。

package com.java2s;

public class StudentsBean implements java.io.Serializable
{
   private String firstName = null;
   private String lastName = null;
   private int age = 0;

   public StudentsBean() {
   }
   public String getFirstName(){
      return firstName;
   }
   public String getLastName(){
      return lastName;
   }
   public int getAge(){
      return age;
   }
   public void setFirstName(String firstName){
      this.firstName = firstName;
   }
   public void setLastName(String lastName){
      this.lastName = lastName;
   }
   public void setAge(Integer age){
      this.age = age;
   }
}

例子

useBean 動(dòng)作在JSP中聲明一個(gè)JavaBean。 useBean標(biāo)記的語(yǔ)法如下:

<jsp:useBean id="bean"s name" scope="bean"s scope" typeSpec/>

scope屬性可以是頁(yè)面,請(qǐng)求,會(huì)話或應(yīng)用程序。

id屬性應(yīng)該是同一JSP中的其他useBean聲明之間的唯一名稱。

下面的代碼顯示了如何使用java Date bean。

<html>
<body>
<jsp:useBean id="date" class="java.util.Date" /> 
<p>The date/time is <%= date %>

</body>
</html>

要獲取JavaBean屬性,請(qǐng)使用< jsp:getProperty/> 動(dòng)作。要設(shè)置JavaBean屬性,請(qǐng)使用<jsp:setProperty/> 動(dòng)作。

<jsp:useBean id="id" class="bean"s class" scope="bean"s scope">
   <jsp:setProperty name="bean"s id" property="property name"  
                    value="value"/>
   <jsp:getProperty name="bean"s id" property="property name"/>
   ...........
</jsp:useBean>

以下代碼顯示如何獲取和設(shè)置StudentBean的屬性。

<html>
<body>
<jsp:useBean id="students" class="com.java2s.StudentsBean"> 
   <jsp:setProperty name="students" property="firstName" value="Jack"/>
   <jsp:setProperty name="students" property="lastName" value="Smith"/>
   <jsp:setProperty name="students" property="age" value="24"/>
</jsp:useBean>

<p>Student First Name: <jsp:getProperty name="students" property="firstName"/>
</p>
<p>Student Last Name: <jsp:getProperty name="students" property="lastName"/>
</p>
<p>Student Age: <jsp:getProperty name="students" property="age"/>
</p>

</body>
</html>

保存在CLASSPATH中可用的StudentsBean.class。



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)