jsp如何调用JavaBean类

2024-12-18 10:26:43
推荐回答(5个)
回答1:

在JSP中调用JavaBean示例代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
< !-- 在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更易于开发和维护。

回答2:

<%@ page import="com.test.*" %> //跟java的import一样,导入类就可以用了

回答3:

<%@ page import="com.test.*" %>

回答4:

//Test.java
package com.test;

public class Test {
public String getMessage(){
return "Hello";
}
}
//Hello.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="com.test.*" %>




Insert title here


<%
Test t=new Test();
out.println(t.getMessage());
%>

回答5:

<%@ page import="包名" %> //先导入包
<%
Test t=new Test(); //实例化类就可以了
%>