1 package example; 2 3 import java.io.PrintWriter ; 4 import java.io.IOException ; 5 6 import java.sql.Connection ; 7 import java.sql.Statement ; 8 import java.sql.ResultSet ; 9 import java.sql.SQLException ; 10 11 import javax.servlet.GenericServlet ; 12 import javax.servlet.ServletRequest ; 13 import javax.servlet.ServletResponse ; 14 import javax.servlet.ServletException ; 15 16 public class SampleServlet extends GenericServlet { 17 public void init() 18 throws ServletException  19 { 20 try { 21 initDatabase(null); 22 } catch (Exception e) { 23 throw new ServletException (e); 24 } 25 } 26 27 @RequireConnection("jdbc/resin") 28 private void initDatabase(Connection conn) 29 throws SQLException  30 { 31 Statement stmt = conn.createStatement(); 32 33 try { 34 ResultSet rs = stmt.executeQuery("SELECT name FROM aop_houses"); 35 if (rs.next()) { 36 rs.close(); 37 stmt.close(); 38 return; 39 } 40 } catch (SQLException e) { 41 } 42 43 String sql = ("CREATE TABLE aop_houses (" + 44 " id INTEGER PRIMARY KEY auto_increment," + 45 " name VARCHAR(255)" + 46 ")"); 47 48 stmt.executeUpdate(sql); 49 50 stmt.executeUpdate("INSERT INTO aop_houses (name) VALUES ('Gryffindor')"); 51 stmt.executeUpdate("INSERT INTO aop_houses (name) VALUES ('Ravenclaw')"); 52 stmt.executeUpdate("INSERT INTO aop_houses (name) VALUES ('Hufflepuff')"); 53 stmt.executeUpdate("INSERT INTO aop_houses (name) VALUES ('Slytherin')"); 54 55 stmt.close(); 56 } 57 58 public void service(ServletRequest request, 59 ServletResponse response) 60 throws IOException , ServletException  61 { 62 response.setContentType("text/html"); 63 64 PrintWriter out = response.getWriter(); 65 66 try { 67 testConnection(out, null); 68 } catch (SQLException e) { 69 throw new ServletException (e); 70 } 71 } 72 73 @RequireConnection("jdbc/resin") 74 private void testConnection(PrintWriter out, Connection conn) 75 throws IOException , SQLException  76 { 77 Statement stmt = conn.createStatement(); 78 ResultSet rs = stmt.executeQuery("SELECT id, name FROM aop_houses"); 79 80 while (rs.next()) { 81 out.println(rs.getInt(1) + ": " + rs.getString(2) + "<br>"); 82 } 83 84 rs.close(); 85 stmt.close(); 86 } 87 } 88 | Popular Tags |