1 import javax.servlet.*; 2 import javax.servlet.http.*; 3 import javax.naming.*; 4 import javax.sql.*; 5 import java.io.*; 6 import java.sql.*; 7 import java.text.*; 8 9 public class JDBCServlet extends HttpServlet { 10 11 DataSource ds; 12 13 public void init() throws ServletException { 14 15 try{ 16 InitialContext initCtx = new InitialContext(); 17 ds = (DataSource)initCtx.lookup("java:comp/env/ToolBoxJDBC"); 18 } 19 catch(Exception e) { 20 System.out.println("! Exception - " + e.getMessage()); 21 e.printStackTrace(); 22 } 23 24 } 25 26 public void service(HttpServletRequest req, HttpServletResponse res) 27 throws ServletException, IOException { 28 29 String KEY = req.getParameterValues("KEY")[0]; 30 31 Connection conn = null; 32 Statement stmt = null; 33 ResultSet rs = null; 34 35 try { 36 37 conn = ds.getConnection(); 38 conn.setAutoCommit(true); 39 stmt = conn.createStatement(); 40 41 rs = stmt.executeQuery("select ITNO, ITCAT, ITDESC, ITPRIC, ITDATE " + 42 "from IPTULIB.ITEM where ITNO = '" + KEY + "'"); 43 44 res.setContentType("text/html"); 45 PrintWriter out = res.getWriter(); 46 47 out.println("Query Result (Servlet)"); 48 out.println("

Query Result (Servlet)


"); 49 50 if (rs.next()) { 51 out.println("
");
  52             out.println("Item number  : " + rs.getString("ITNO"));
  53             out.println("category     : " + rs.getString("ITCAT"));
  54             out.println("description  : " + rs.getString("ITDESC"));
  55             DecimalFormat df = new DecimalFormat("###,###,##0.00");
  56             out.println("unit price   : " + df.format(rs.getInt("ITPRIC")));
  57             out.println("date         : " + rs.getDate("ITDATE"));
  58             out.println("
"); 59 } 60 else { 61 out.println("

Item not found." + 62 "(KEY=" + KEY + ")

"); 63 } 64 out.println("Return"); 65 out.println(""); 66 out.flush(); 67 out.close(); 68 69 rs.close(); 70 rs = null; 71 stmt.close(); 72 stmt = null; 73 conn.close(); 74 conn = null; 75 76 } catch(Exception e) { 77 e.printStackTrace(); 78 79 } finally { 80 81 if (rs != null) { 82 try { rs.close(); } catch (SQLException e) { ; } 83 rs = null; 84 } 85 if (stmt != null) { 86 try { stmt.close(); } catch (SQLException e) { ; } 87 stmt = null; 88 } 89 if (conn != null) { 90 try { conn.close(); } catch (SQLException e) { ; } 91 conn = null; 92 } 93 94 } 95 96 } 97 98 }