如何使用useBean 並舉一個簡單的範例
1.使用jsp:useBean來存放javaBean讓程式看起來比較簡單
2.首先先定義一個java bean 叫UserData
有3個成員, firstName , lastName ,age
使用netBeans的生成工具快速產生get 和set的方法
宣告完變數後,在空白的地方按右鍵,選Insert Code... -->Getter and Setter...
UserData.java
package bean;
public class UserData {
private String firstName;
private String lastName;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
3.先寫輸入的畫面,會傳三個參數到SaveName.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<form method="post" action="SaveName.jsp">
First name: <input type="text" name=firstName ><br>
Last Name: <input type="text" name=lastName ><br>
Age: <input type="text" name=age ><br>
<input type="submit" name="submit" value="Save">
</form>
4.用setProperty把參數接下來並只到一開始所寫的bean.UserData ,注意一定要給useBean 一個id
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="bean.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<A HREF="showPage.jsp">Continue</A>
5.最後再把剛才輸入的值秀出來
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="bean.UserData" scope="session"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
You entered<BR>
First Name: <%= user.getFirstName() %><BR>
Last Name: <%= user.getLastName() %><BR>
Age: <%= user.getAge() %><BR>