JSP之使用useBean、setProperty、getProperty指令

來源:互聯網
上載者:User

標籤:

useBean指令用於在JSP頁面中初始化一個Java執行個體,setProperty指令用於為JavaBean執行個體的屬性設定值,getProperty指令用於輸出JavaBean執行個體的屬性。

例子:

JavaBean代碼如下:

package zhou;

public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

public Person(){}
public Person(String name,int age){
this.name=name;
this.age=age;
}

}

JSP頁面代碼如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="p1" class="zhou.Person" scope="page"></jsp:useBean>
<jsp:setProperty name="p1" property="name" value="zhou" />
<jsp:setProperty name="p1" property="age" value="18" />
<jsp:getProperty name="p1" property="name" />
<jsp:getProperty name="p1" property="age" />
</body>
</html>

由於為web應用提供了新的class,所以需要重啟tomcat,頁面運行結果:

zhou 18

但是在練習的過程中,也發現如下問題:

(1)如果Person類不放在命名包中,而是預設包,發現在JSP中無法訪問該JavaBean;

(2)如果在頁面頭部通過import指令匯入JavaBean所在的包,

<%@ page language="java" import="zhou.*" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

在使用useBean指令時不指明JavaBean所在的包,即

<jsp:useBean id="p1" class="Person" scope="page"></jsp:useBean>

 發現也不能訪問該JavaBean。

JSP之使用useBean、setProperty、getProperty指令

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.