在JSP中调用JavaBean示例代码如下:
< !-- 在jSP中使用JavaBean一般遵循以下四步
(1)导入JavaBean的类
(2) 在指定范围内实例化一个JavaBean对象,如果该对象已经存在则直接引用
(3) 对Javabean的实例对象进行操作
(4)从指定范围内移除JavaBean
-->
< %@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
< %@page import="JavaBeanTest.CircleArea" %>
< jsp:useBean id="circle1" class="JavaBeanTest.CircleArea" scope="page"/>
< jsp:useBean id="circle2" class="JavaBeanTest.CircleArea" scope="request"/>
< jsp:useBean id="circle3" class="JavaBeanTest.CircleArea" scope="session"/>
< jsp:useBean id="circle4" class="JavaBeanTest.CircleArea" scope="application" />
JavaBean在JSP中的应用< %
//调用page范围内的JavaBean
circle1.setR(4);
circle1.setUnit("米");
out.println(circle1.getArea());
out.println("
");
//调用request范围内的JavaBean
circle1.setR(6);
circle1.setUnit("米");
out.println(circle1.getArea());
out.println("
");
//调用session范围内的JavaBean
circle1.setR(8);
circle1.setUnit("米");
out.println(circle1.getArea());
out.println("
");
//调用application范围内的JavaBean
circle1.setR(9);
circle1.setUnit("米");
out.println(circle1.getArea());
out.println("
");
%>
//将circle1从page范围内移除
pageContext.removeAttribute("circle1");
//将circle2从request范围内移除
request.removeAttribute("circle2");
//将circle3从session范围内移除
session.removeAttribute("circle1");
//将circle4从application范围内移除
application.removeAttribute("circle1");
%>
< /html>
在JSP中使用JavaBean,可以实现HTML代码和Java代码的分离,使JSp更易于开发和维护。
取消
评论