引言:html
1. JavaBeans的編寫要求java
2. 一個簡單的JavaBeans實例web
01: package myBean;瀏覽器
02: import java.io.*;服務器
03: public class HelloBeansession
04: {app
05: //定義屬性webapp
06: private String name="Hello Bean";jsp
07: //定義無參的構造函數函數
08: public HelloBean(){}
09: //定義獲取屬性的getXXX方法
10: public String getName()
11: {
12: return name;
13: }
14: //定義設置屬性的setXXX方法
15: public void setName(String str)
16: {
17: name=str;
18: }
19: public static void main(String[] args)
20: {
21: System.out.println("Example JavaBeans");
22: }
23: }
3. 在JSP中使用JavaBeans
01: <%@page contentType="text/html;charset=GBK"%>
02: <HTML>
03: <HEAD><TITLE>使用JavaBeans</TITLE>
04: </HEAD>
05: <BODY>
06: <H2>該實例說明了在一個JSP中如何使用JavaBeans的屬性</H2>
07: <HR>
08:<jsp:useBean id="myBean" class="myBean.HelloBean" scope="application"/>
09: 調用setProperty前name屬性的值是:
10: <jsp:getProperty name="myBean" property="name" />
11: <P>
12: <jsp:setProperty name="myBean" property="name" value="Hello World"/>
13: 調用setProperty後name屬性的值是:
14: <jsp:getProperty name="myBean" property="name" />
15: </BODY>
16: </HTML>
1. jsp:useBean操做
<jsp:useBean id=「beanName」
scope="page|request|session|application「
class="package.class"
/>
2. jsp:setproperty操做
<jsp:setProperty name="beanName "
property="propertyName"
value="propertyValue「
/>
<jsp:useBean id="beanName " ... >
..
<jsp:setProperty name=" beanName " property=" propertyName" value="propertyValue" />
</jsp:useBean>
3. jsp:getProperty操做
<jsp:getProperty name="beanName " property="propertyName" />
================================================================
如下代碼是我根據上面的說明,寫的簡單的測試:
方式一:
package Java.Bean; import java.util.Date; import java.text.*; public class Test1 { public Test1(){} public String say() { String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); return " Welcome! Now :"+time; } } -------------------------------------- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="Java.Bean.*"%> <html> <body> <h1>Hi <%= new Java.Bean.Test1().say()%></h1> </body> </html>
方式二:
package mybean; public class Test1 { public Test1(){} public String say() { return " Welcome Java Bean."; } } -------------------------------------------- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <jsp:useBean id="my" scope="request" class="mybean.Test1"></jsp:useBean> <html> <body> <h1>Hi <%=my.say()%></h1> </body> </html>