JavaBean示例
首先寫了一個名稱爲Sudents.java的共有的javaBean,然後用其實現兩個示例
- 在testBean01.jsp中 設置了各個屬性,並顯示
- 在testBean02.jsp中 讓用戶輸入各個屬性,點擊提交之後並顯示在頁面上
Students.java
package com.health;
public class Students {
private String name;
private String age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
示例一
testBean01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:useBean id="stu" class="com.health.Students" scope="page" />
<jsp:setProperty name="stu" property="name" value="劉邦"/>
<jsp:setProperty name="stu" property="age" value="21"/>
<jsp:setProperty name="stu" property="sex" value="男"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>測試 Students Bean</title>
</head>
<body>
姓名:<jsp:getProperty name="stu" property="name"/><br>
年齡:<jsp:getProperty name="stu" property="age"/><br>
性別:<jsp:getProperty name="stu" property="sex"/>
</body>
</html>
<jsp:useBean id="stu" class="com.health.Students" scope="page" />:類似於實例化一個名爲stu的對象
scope:表示該實例的生存範圍,取值有 page(默認值)、request、session、application
運行結果:
示例二
testBean02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<!--通過useBean動作標籤引入一個id爲stu, Java類爲Students的Bean實例-->
<jsp:useBean id="stu" class="com.health.Students" scope="page" />
<!--利用表單beanTest中用戶輸入的值爲stu設置屬性值-->
<jsp:setProperty name="stu" property="*" />
<html>
<head>
<meta charset="UTF-8">
<title>測試 Students Bean02</title>
</head>
<body>
<!-- 獲取stu的各個屬性的值並顯示 -->
姓名:<jsp:getProperty name="stu" property="name" /><br>
年齡:<jsp:getProperty name="stu" property="age" /><br>
性別:<jsp:getProperty name="stu" property="sex" />
<form method="post" action="testBean02.jsp">
<!-- 通過用戶輸入 爲stu各屬性賦值 -->
輸入姓名:<input type="text" name="name"><br>
輸入年齡:<input type="text" name="age"><br>
輸入性別:<input type="text" name="sex"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
運行結果:
輸入信息 點 提交之後