Java完成JSP在Servelt中銜接Oracle數據庫的辦法。本站提示廣大學習愛好者:(Java完成JSP在Servelt中銜接Oracle數據庫的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java完成JSP在Servelt中銜接Oracle數據庫的辦法正文
本文實例講述了Java完成JSP應用Servelt銜接Oracle數據庫的辦法。為了完成在Servlet 中銜接數據庫,必需編寫Servlet 的類法式。將Servlet 類法式放到WEB 辦事器的servlets 或許classes 目次上面,為挪用Servlet,須要創立發送Servlet 要求的HTML 文檔。本例經由過程(Driver)Class.forName(driverName).newInstance()辦法來完成加載驅動法式,樹立與數據庫銜接。
詳細法式代碼為:
1.Database 類繼續了HttpServlet 類,共有兩個辦法:doGet()和displayResult(),代碼以下:
public class Database extends HttpServlet { public void doGet(); public void displayResult(ResultSet results,PrintWriter out); }
2.在doGet()辦法中樹立與數據庫的銜接並履行查詢:
public void doGet() { HttpServletRequest request, HttpServletResponse response } throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet connecting to Oracle DB"; response.setContentType("text/html;charset=GB2312"); out = response.getWriter(); out.println("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); String driverName = "oracle.jdbc.driver.OracleDriver"; Driver d; Connection con; Statement stmt; ResultSet results; try { d = (Driver)Class.forName(driverName).newInstance(); con = DiverManager.getConnection("jdbc:oracle:thin:ndb/[email protected]:1521:PC6"); stmt = con.createStatement(); String sqlstr = "select * from data"; results = stmt.executeQuery(sqlstr); displayResult(results,out); stmt.close(); con.close(); } catch (Exception e) { out.println("error: " + e.toString()); } out.println("</BODY></HTML>"); out.close(); }
3.DisplayResult()辦法顯示查詢成果:
public void displayResult(ResultSet results,PrintWriter out) { StringBuffer buf = new StringBuffer(); String temp; try { ResultSetMetaData rsmd = results.getMetaData(); int numCols = rsmd.getColumnCount(); int i, rowcount = 0; for (i=1; i <= numCols; i++) { if (i > 1) buf.append(","); buf.append(rsmd.getColumnLabel(i)); } buf.append(""); while (results.next() && rowcount < 100) { for (i=1; i <= numCols; i++) { if (i > 1) buf.append(","); buf.append((results.getString(i))); } buf.append("<br>"); rowcount++; } out.println("<br>"); out.println(buf.toString()); results.close(); } catch (Exception e) { out.println("error: " + e.toString()); return; } }
4.由於法式應用了JDBC 類、servlet 類和應用掌握台輸入,所以須要引入以下的包:
import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
5.編譯Database.java,發生Database.class 文件,將Database.class 放到WEB 辦事器的servlets 目次下,本例采取Java Web Server 作為WEB 辦事器。設置裝備擺設好WEB 辦事器,添加database.class,指命名稱為database。
6.編寫挪用Servlet 的database.html 文件。代碼以下:
<html> <head> <title>Jsp應用Servlet銜接數據庫</title> </head> <body> <center> <form action="/servlet/database" method="get"> <input name="action" type="submit" value="銜接數據庫"> </form> </center> </body> </html>