|
|
| JSP技术生成动态web页面 |
| 作者:无从考证 来源:转载 发布时间:2005-11-3 13:13:04 发布人:admin |
减小字体
增大字体
用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 上一页 [1] [2]
|
| |
|
[]
[返回上一页]
[打 印]
[收 藏] |
|
| ∷相关文章评论∷ (评论内容只代表网友观点,与本站立场无关!) [更多评论...] |
|
|