1 package example; 2 3 import java.io.PrintWriter ; 4 5 import java.sql.Connection ; 6 import java.sql.Statement ; 7 import java.sql.ResultSet ; 8 import java.sql.SQLException ; 9 10 import javax.sql.DataSource ; 11 12 import javax.naming.InitialContext ; 13 import javax.naming.Context ; 14 import javax.naming.NamingException ; 15 16 import javax.servlet.ServletException ; 17 18 import javax.servlet.http.HttpServlet ; 19 import javax.servlet.http.HttpServletRequest ; 20 import javax.servlet.http.HttpServletResponse ; 21 22 23 27 public class InitServlet extends HttpServlet { 28 31 private DataSource _ds = null; 32 33 36 public void setDataSource(DataSource ds) 37 { 38 _ds = ds; 39 } 40 41 44 public void init() 45 throws ServletException 46 { 47 try { 48 if (_ds == null) 49 assemble(); 50 51 Connection conn = _ds.getConnection(); 52 53 try { 54 Statement stmt = conn.createStatement(); 55 56 try { 57 ResultSet rs = stmt.executeQuery("SELECT id FROM jdbc_basic_brooms"); 58 59 if (rs.next()) { 60 rs.close(); 61 stmt.close(); 62 return; } 64 } catch (SQLException e) { 65 } 66 67 stmt.executeUpdate("CREATE TABLE jdbc_basic_brooms (" + 68 " id INTEGER PRIMARY KEY auto_increment," + 69 " name VARCHAR(128)," + 70 " cost INTEGER" + 71 ")"); 72 stmt.executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) " + 73 "VALUES ('firebolt', 4000)"); 74 stmt.executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) " + 75 "VALUES ('nimbus 2001', 500)"); 76 stmt.executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) " + 77 "VALUES ('nimbus 2000', 300)"); 78 stmt.executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) " + 79 "VALUES ('cleansweep 7', 150)"); 80 stmt.executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) " + 81 "VALUES ('cleansweep 5', 100)"); 82 stmt.executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) " + 83 "VALUES ('shooting star', 50)"); 84 85 stmt.close(); 86 } finally { 87 conn.close(); 88 } 89 } catch (SQLException e) { 90 throw new ServletException (e); 91 } 92 } 93 94 98 private void assemble() 99 throws ServletException 100 { 101 try { 102 String dataSourceName = getInitParameter("data-source"); 103 104 if (dataSourceName == null) 105 dataSourceName = "jdbc/basic"; 106 107 Context ic = new InitialContext (); 108 109 _ds = (DataSource ) ic.lookup("java:comp/env/" + dataSourceName); 110 111 if (_ds == null) 112 throw new ServletException (dataSourceName + " is an unknown data-source."); 113 } catch (NamingException e) { 114 throw new ServletException (e); 115 } 116 } 117 118 121 public void service(HttpServletRequest req, HttpServletResponse res) 122 throws java.io.IOException , ServletException 123 { 124 throw new UnsupportedOperationException (); 125 } 126 } 127 | Popular Tags |