隨著WEB技術的發展,WEB內容從一些靜態的頁到內容豐富的動態頁。對于廣大WEB開發人員來講動態頁面的生成是一個挑戰。有許多的方法來試圖解決這個問題,如plug-in技術及基于服務器端的APIs等方法,但存在的一個問題是這些方法是針對某個特定的web服務器,如Microsoft提供的ASP技術就只針對它的IIS及Personal web服務器。 } [page_break]用JDK編譯該文件: javac helloWorld.java 在成功編譯后,將生成的字節碼文件HelloWorld.class放到myweb/web-inf/jsp/beans目錄下; 在下面jsp文件test.jsp中調用helloWorld,test.jsp內容如下: <html> <head> <title> Jsp and java bean </title> </head> <body> <jsp:useBean id="helloBean" scope="session" class="HelloWorld" /> <% String hello = "this is a bean test"; helloBean.setHello(hello); out.println(helloBean.sayHello() + "<br>"); %> </body> </html> 將該jsp文件放到jswdk_install\myweb\目錄下 重新啟動web Server,在瀏覽器地地址中輸入: http://localhost:8080/myweb/test.jsp 就可以顯示執行結果; 注意到在test.jsp中 <jsp:useBean id="helloBean" scope="session" class="HelloWorld" /> 的scope = "session"表明該對象創建后可在同一會話(session)的其它頁引用。如我們可以在aftertest.jsp中引用test.jsp中創建的對象,aftertest.jsp內容包含下面的代碼: <% helloWorld rebean = (helloWorld)session.getValue("helloBean"); out.println("bean used in aftertest.jsp"+rebean.sayHello()); %> 要注意的是要引用的對象必須已創建,否則會出現異常。 下面看看在jsp中使用訪問數據的java beans例子。我所使用的數據庫是oracle8,通過SQL*Net創建的數據庫連接串名為begpinter,數據庫服務器運行在名為begpinterserver的機器上,下面是JspJdbc.java的內容: // You need to import the java.sql package to use JDBC import java.sql.*; import oracle.jdbc.driver.* ; public class JspJdbc { Connection conn = null; Public ResultSet rset = null; public JdbcCheckup(){ // Load the Oracle JDBC driver try{ DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); }catch(SQLException e1) { System.err.println("executeQuery: " + e1.getMessage()); } } public ResultSet executeQuery(String sql) { rset = null; try { conn = DriverManager.getConnection ("jdbc:oracle:thin:@bgpinterserver:1521:bgpinter","SCOTT", "TIGER"); Statement stmt = conn.createStatement(); rset = stmt.executeQuery(sql); }catch(SQLException e1) { System.err.println("error: " + e1.getMessage()); } return rset; } } 編譯后將JspJdbc.class文件放入myweb\web-inf\jsp\beans目錄下。在下面的jsp文件中調用beans,jspdb.jsp內容如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>Database in Jsp</title> </head> <body> <%@ page language="java" import="java.sql.*,oracle.jdbc.driver.*" errorPage="errorpage.jsp" %> <jsp:useBean id="jspdatabase" scope="page" class="JspJdbc" /> <% ResultSet rset = jspdatabase.executeQuery("SELECT * FROM emp"); out.println("<table><tr><th>number</th><th>name</th></tr>"); while (reset.next()) { out.println("<tr><td>"+rset.getInt("eptno")+"</td>"); out.println("<td>"+rset.getString("enameeptno")+"</td></tr>"); } rest.close(); out.println("</table>"); %> </body> </html> 其中用于顯示異常的errorpage.jsp內容為: <html> <body bgcolor="red"> <%@ page isErrorPage="true" %> <h1> The exception <%= exception.getMessage() %> </body> </html> 重新啟動Web server使新創建的java beans生效,如果與數據服務器連接正常,則在瀏覽器地址中輸入 http://localhost:8080/myweb/jspdb.jsp 將顯示查詢結果。 通過上面的介紹,相信大家對Jsp有所了解。要進一步了解Jsp技術可訪問下面的站點: http://java.sun.com/products/jsp |
溫馨提示:喜歡本站的話,請收藏一下本站!