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>
运行结果:
输入信息 点 提交之后