JavaBeans是一个可重复使用的软件部件,用来生成其进行可视化处理的部件。
JavaBeans组件是一个JAVA类,遵循一个接口格式,以便于把类看做标准的JavaBeans组件进行构造。
JavaBeans的属性
属性是Bean组件内部状态的抽象表示。JavaBeans的属性可以分为以下四类:
◆ Simple 简单的
◆ Indexed 索引的
◆ Bound 绑定的
◆ Constrained 约束的
简单属性依赖于标准命名约定来定义getXXX()方法和setXXX()方法。索引属性则允许读取和设置整个数组,也允许使用数组索引单独地读取和设置数组元素。绑定属性则是其值发生变化时要广播给属性变化监听器的属性。约束属性则是那些值发生改变及起作用之前,必须由约束属性变化监听器生效的属性。
1、 Simple 简单属性:表示一个伴随有Get/Set方法的变量。
例程1:[formInput.java]
package Test;
public class formInput{
String str = new String("New Year");
public formInput(){
}
public void setInput(String str){
this.str = str;
}
public String getInput(){
return str;
}
}
2、 Indexed 索引属性:表示一个数组值,可以使用Get/Set方法取得数组中的值。
例程2:[formInput1.java]
package Test;
public class formInput1{
String b[] = new String[]{
"5","2","3","4"
};
public formInput1(){
}
public String[] getInput(){
return b;
}
public void setInput(String[] b){
this.b = b;
}
}
3、 Bound 绑定属性:提供一种机制,即通知监听器一个JavaBeans组件的属性发生了改变。
例程3:[boundBean.java]
package Test;
import java.awt.Canvas;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class boundBean extends Canvas{
String str = "bound Bean";
private PropertyChangeSupport propertyChange = new PropertyChangeSupport(this);
public void setString(String newValue){
String oldValue = str;
str = newValue;
propertyChange.firePropertyChange("change value",oldValue,newValue);
}
public String getString(){
return str;
}
public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener){
propertyChange.addPropertyChangeListener(propertyChangeListener);
}
public void removePropertyChangeListener(PropertyChangeListener propertyChangeListener){
propertyChange.removePropertyChangeListener(propertyChangeListener);
}
}
4、 Constrained 约束属性:与绑定属性类似,但属性值的变化首先要被所有的监听器验证以后,值的变化才能由JavaBeans组件发生作用。
例程4:[constrainedBean.java]
package Test;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
public class constrainedBean{
//实例化一个propertyChange对象
private PropertyChangeSupport propertyChange = new PropertyChangeSupport(this);
//实例化一个vetoChange对象
private VetoableChangeSupport vetoChange = new VetoableChangeSupport(this);
public void setUsername(String newUsername){
try{
String oldUsername=yourName;
vetoChange.fireVetoableChange("Username",new String(oldUsername),new String(newUsername));
yourName=newUsername;
changes.firePropertyChange("Username",new String(oldPriceInCents),new String(newUsername));
}
catch(PropertyVetoException e){
System.err.println(e.getMessage());
}
public void addVetoableChangeListener(VetoableChangeListener vetoableChangeListener){
vetos.addVetoableChangeListener(vetoableChangeListener);
}
public void removeVetoableChangeListener(VetoableChangeListener vetoableChangeListener){
vetos.removeVetoableChangeListener(vetoableChangeListener);
}
}
}
JavaBeans的应用
1、 猜数字
目的:程序指定一个1~100之间的某一个自然数,然后用户去猜这个数的值是多少。程序会根据用户的输入值,做出相应的信息提示。
代码:
[numguess.jsp]
<%@ page contentType="text/html;charset=gb2312" %>
<jsp:useBean id="numguess" class="Test.NumGuessBean" scope="session" />
<jsp:setProperty name="numguess" property="*" />
<html>
<head>
<title>Number Guess</title>
</head>
<body>
<font size=4>
<% if(numguess.getSuccess()){ %>
Congratulations! You got it.
And after just <%= numguess.getNumGuesses() %>tries.<p>
<% numguess.reset(); %>
Care to <a href="numguess.jsp">try again</a>?
<% }
else if(numguess.getNumGuesses() == 0){ %>
Welcome to the Number Guess Game.<p>
I'm thinking of a number between 1 and 100.<p>
<form method="get">
What's your guess?<input type=text name="guess">
<input type="submit" value="Submit">
</form>
<% } else { %>
Good guess,but nope. Try <b><%= numguess.getHint() %></b>
You have made <%= numguess.getNumGuesses() %> guesses.<p>
I'm thinking of a number between 1 and 100.<p>
<form method="get">
What's your guess?<input type=text name="guess">
<input type="submit" value="Submit">
</form>
<% } %>
</font>
</body>
</html>
该程序用到一个Bean,代码:
[NumGuessBean.java]
package Test;
import java.util.*;
public class NumGuessBean{
int answer;
boolean success;
String hint;
int numGuesses;
public NumGuessBean(){
reset();
}
public void setGuess(String guess){
numGuesses++;
int g;
try{
g = Integer.parseInt(guess);
}
catch(NumberFormatException e){
g = -1;
}
if(g == answer){
success = true;
}
else if(g == -1){
hint = "a number next time";
}
else if(g < answer){
hint = "higher";
}
else if(g > answer){
hint = "lower";
}
}
public boolean getSuccess(){
return success;
}
public String getHint(){
return "" + hint;
}
public int getNumGuesses(){
return numGuesses;
}
public void reset(){
answer = Math.abs(new Random().nextInt() % 100) + 1;
success = false;
numGuesses =0;
}
}
2、 封装数据库
目的:用JavaBeans封装数据库操作。采用的数据库是SQL Server。
步骤:首先,建立数据库Vote,在其中建立表voter和result.
表voter的作用是存放投票人的资料,其结构为:
字段名
描述
数据类型
id
自动
Int
Candidate
投票的公司
Varchar
voter_name
投票人姓名
Varchar
voter_company
投票人所在的公司
Varchar
voter_country
投票人所在的国家
Varchar
ip_address
投票人的IP地址
Varchar
vote_time
投票时间
datetime
表result的作用是存放候选人的票数,其结构为:
字段名
描述
数据类型
id
自动
Int
candidate
候选公司
Varchar
vote_num
票数
int
建立完数据库后,在ODBC数据源管理器中加入系统DSN,取名vote。
创建一个JavaBeans,取名为conn.java。
代码:
package vote;
import java.sql.*;
public class conn{
String sDBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String sConnStr = "jdbc:odbc:vote";
Connection connect = null;
ResultSet rs = null;
public conn(){
try{
Class.forName(sDBDriver);
}
catch(java.lang.ClassNotFoundException e){
System.err.println(e.getMessage());
}
}
public ResultSet executeQuery(String sql){
rs = null;
try{
connect = DriverManager.getConnection(sConnStr);
Statement stmt = connect.createStatement();
rs = stmt.executeQuery(sql);
}
catch(SQLException ex){
System.err.println(ex.getMessage());
}
return rs;
}
}
编译后放置在应用服务器\WEB_INF\classes\vote目录下。
页面代码:[show.jsp]
<%@ page contentType="text/html;charset=gb2312" %>
<%@ page language="java" import="java.sql.*" %>
<jsp:useBean id="voteBean" scope="page" class="vote.conn" />
<html>
<head>
<title>当前票数统计</title>
<meta http-equiv="refresh" content="10;URL=show.jsp">
</head>
<body align=center>
<h1><b>当前票数统计</b></h1>
<table width="60%" border=1>
<tr bgcolor="#ccccff" align=center>
<td width="51%"><font color="#ff0033"><b>候选公司名</b></font></td>
<td width="49%"><font color="#ff0033"><b>当前票数</b></font></td>
</tr>
<%
ResultSet RS_result;
RS_result = voteBean.executeQuery("select * from result");
String companyName;
int voteNum;
while(RS_result.next()){
companyName = RS_result.getString("candidate");
voteNum = RS_result.getInt("vote_num");
%>
<tr align=center>
<td><%=companyName%></td>
<td><%=voteNum%></td>
</tr>
<%
}
RS_result.close();
%>
</table>
<hr>
<h2><b>投票人的详细信息</b></h2>
<table width="100%" border="1">
<tr bgcolor="#ffcccc" align="center">
<td><font color="#0000ff"><b>投票的公司</b></font></td>
<td><font color="#0000ff"><b>投票人姓名</b></font></td>
<td><font color="#0000ff"><b>投票人所在的公司</b></font></td>
<td><font color="#0000ff"><b>投票人所在的国家</b></font></td>
<td><font color="#0000ff"><b>投票人的IP地址</b></font></td>
<td><font color="#0000ff"><b>投票时间</b></font></td>
</tr>
<%
ResultSet RS_voter;
RS_voter = voteBean.executeQuery("select * from voter");
String candidate,voterName,voterCompany,voterCountry,ipAddress;
java.util.Date voteTime;
while(RS_voter.next()){
candidate = RS_voter.getString("candidate");
voterName = RS_voter.getString("voter_name");
voterCompany = RS_voter.getString("voter_company");
voterCountry = RS_voter.getString("voter_country");
ipAddress = RS_voter.getString("ip_address");
voteTime = RS_voter.getDate("vote_time");
%>
<tr>
<td> <%=candidate%></td>
<td> <%=voterName%></td>
<td> <%=voterCompany%></td>
<td> <%=voterCountry%></td>
<td> <%=ipAddress%></td>
<td> <%=voteTime%></td>
</tr>
<%
}
RS_voter.close();
%>
</table>
</body>
</html>