Ниже приводится пример файла
, программирующего Java-сервлет, выдающий в браузер перечень сотрудников из схемы SCOTT
import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class StaffByServletTransactional extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); } catch (Exception e) { } } public void doGet( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Per Transaction Connection</title>"); out.println("</head>"); out.println("<body>"); out.println("<pre>"); Connection cn = null; try { cn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:teacher", "scott", "tiger"); } catch (Exception e) { } Statement st = null; ResultSet rs = null; try { st = cn.createStatement(); rs = st.executeQuery("SELECT empno, ename FROM emp"); while (rs.next()) { out.println("Number=" + rs.getString(1) + " " + "Name=" + rs.getString(2)); } st.close(); cn.close(); } catch (Exception e) { } out.println("</pre>"); out.println("<hr>"); out.println("</body>"); out.println("</html>"); } public void doPost( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } } |
Трансляция сервлета:
SET CLASSPATH=%ORACLE_HOME%\lib\servlet.jar;.
javac StaffByServletTransactional.java