JavaBean是一个特殊的类。
•JavaBean的设计规则
•(1)JavaBean是一个公共类。
•(2)JavaBean类具有一个公共的无参的构造方法。
•(3)JavaBean所有的属性定义为私有的。
•(4)在JavaBean中,需要对每个属性提供两个公共方法。假设属性名字是xxx,要提供的两个方法:
•setXxx():用来设置属性xxx的值。
•getXxx():用来获取属性xxx的值(若属性类型是boolean,则方法名为isXxx())。
•(5)定义JavaBean时,通常放在一个命名的包下。
例:使用Javabean设计一个求圆的面积周长
步骤:1,首先建立一个Javaweb工程,
2,然后在工程中的 Java Resources 的src下建立javabean的包,
3,在包中写javabean的类
4,在Webcontent中建立jsp文件,显示圆的面积和周长
注意:在jsp文件中要导入javabean 的包,格式为<%@page import="beans.Circle" %>
圆的类代码:
package beans;
public class Circle {
private double radius;
private double x;
private double y;
private String color;
private boolean fill;
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFill() {
return fill;
}
public void setFill(boolean fill) {
this.fill = fill;
}
public Circle() {}//无参构造函数
public Circle(double radius, double x, double y, String color, boolean fill) {
super();
this.radius = radius;
this.x = x;
this.y = y;
this.color = color;
this.fill = fill;
}
public double Area()
{
return 3.14*radius*radius;
}
public double CircleLength()
{
return 2*3.14*radius;
}
}
显示页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@page import="beans.Circle" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>显示圆的面积和周长</title>
</head>
<body>
<%
Circle c=new Circle(1,1,1,"red",true);
double area=c.Area();
double clength=c.CircleLength();
out.println(area+" "+clength);
%>
</body>
</html>