JSP编程技术学习笔记(三)JavaBean(一)

JavaBean实例

新建如下项目——新建包——新建类……

JavaBean的使用步骤

  1. 导入JavaBean  <%@ page import="包名.类名"%>
  2. 声明JavaBean  <jsp:useBean id="id" class="包名.类名"></jsp:useBean>
  3. 访问JavaBean属性

注:id可以取任意值,使用getProperty/setProperty中name="id";要保证前后id一致。

实例一:

一:在tsc包中新建Circle类

package tsc;

public class Circle {
	int radius = 1;

	public Circle(int radius) {
		super();
		this.radius = radius;//可以去掉,
	}

	public Circle() {// 必须有

	}

	public int getRadius() {
		return radius;
	}

	public void setRadius(int radius) {
		this.radius = radius;
	}

	public double getArea() {
		return Math.PI * radius * radius;
	}

}

二:在WebContent下新建jweb.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="tsc.*"%><%--导入JavaBean--%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<jsp:useBean id="c1" class="tsc.Circle"></jsp:useBean><%--声明JavaBean--%>
	<h1>
		圆的默认半径:<jsp:getProperty property="radius" name="c1" />
		<br>修改圆的半径:<jsp:setProperty property="radius" name="c1"
			value="100" />
		<br>修改后圆的半径:<jsp:getProperty property="radius" name="c1" />
		<br>圆的面积:<%=c1.getArea()%>
		<hr size="3" color="red">
		<br>使用java语句<br>
		<%
			Circle c2 = new Circle(20);
			out.print("圆的默认半径:" + c2.getRadius() + "<br>");
			out.print("修改圆的半径:<br>");
			c2.setRadius(100);
			out.print("修改后圆的半径:" + c2.getRadius() + "<br>");
			out.print("圆的面积:" + c2.getArea());
		%>
	</h1>
</body>
</html>

运行效果:

倘若,不使用JavaBean可写为例jweb1.jsp如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%!public class Circle {
		int radius = 1;

		public Circle(int radius) {
			super();
			this.radius = radius;// 可以去掉
		}

		public Circle() {// 必须有

		}

		public int getRadius() {
			return radius;
		}

		public void setRadius(int radius) {
			this.radius = radius;
		}

		public double getArea() {
			return Math.PI * radius * radius;
		}

	}%>
	<%
		Circle c = new Circle(20);
		out.print(c.getArea());
	%>
</body>
</html>

运行结果:

1256.6370614359173 

综上,可以看出,对于编写简单的jsp页面时,使用JavaBean时效果并不是很明显。但是,如jweb1.jsp来说,当大量的java代码嵌入到网页中时,会使程序看起来结构混乱,不利于程序员的阅读调试……

所以,JavaBean会使得JSP编程模式变得更加清晰,程序可读性强。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值