JavaBean learning summary

Posted by cnperry on Fri, 15 Nov 2019 17:55:58 +0100

JavaBean is a special class.

• design rules for JavaBean s

(1) JavaBean is a public class  

• (2) the JavaBean class has a common parameterless constructor.

(3) all properties of JavaBean s are defined as private.

• (4) in JavaBean s, you need to provide two public methods for each attribute. Suppose the property name is xxx. There are two methods to provide:

Set xxx(): used to set the value of property XXX.

getXxx(): used to get the value of property xxx (if the property type is boolean, the method name is isXxx()).

(5) JavaBean s are usually defined under a named package.

Example: using java bean to design the area perimeter of a circle

Steps: 1. First, build a Java Web project,

2, and then build the package of JavaBeans under the src of Java Resources in the project,

3, write the class of javabean in the package

4. Create a jsp file in Webcontent to display the area and perimeter of the circle

Note: to import the package of javabean in jsp file, the format is <% @ page import = "beans. Circle"% >

Class code of 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() {}//non-parameter constructor 
	
	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;
	}
}

Display page:

<%@ 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>Display the area and perimeter of the circle</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>

 

Topics: Java JSP Attribute