KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > SampleServlet


1 package example;
2
3 import java.io.PrintWriter JavaDoc;
4 import java.io.IOException JavaDoc;
5
6 import java.sql.Connection JavaDoc;
7 import java.sql.Statement JavaDoc;
8 import java.sql.ResultSet JavaDoc;
9 import java.sql.SQLException JavaDoc;
10
11 import javax.servlet.GenericServlet JavaDoc;
12 import javax.servlet.ServletRequest JavaDoc;
13 import javax.servlet.ServletResponse JavaDoc;
14 import javax.servlet.ServletException JavaDoc;
15
16 public class SampleServlet extends GenericServlet JavaDoc {
17   public void init()
18     throws ServletException JavaDoc
19   {
20     try {
21       initDatabase(null);
22     } catch (Exception JavaDoc e) {
23       throw new ServletException JavaDoc(e);
24     }
25   }
26
27   @RequireConnection("jdbc/resin")
28   private void initDatabase(Connection JavaDoc conn)
29     throws SQLException JavaDoc
30   {
31     Statement JavaDoc stmt = conn.createStatement();
32
33     try {
34       ResultSet JavaDoc rs = stmt.executeQuery("SELECT name FROM aop_houses");
35       if (rs.next()) {
36     rs.close();
37     stmt.close();
38     return;
39       }
40     } catch (SQLException JavaDoc e) {
41     }
42
43     String JavaDoc 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 JavaDoc request,
59               ServletResponse JavaDoc response)
60     throws IOException JavaDoc, ServletException JavaDoc
61   {
62     response.setContentType("text/html");
63     
64     PrintWriter JavaDoc out = response.getWriter();
65
66     try {
67       testConnection(out, null);
68     } catch (SQLException JavaDoc e) {
69       throw new ServletException JavaDoc(e);
70     }
71   }
72
73   @RequireConnection("jdbc/resin")
74   private void testConnection(PrintWriter JavaDoc out, Connection JavaDoc conn)
75     throws IOException JavaDoc, SQLException JavaDoc
76   {
77     Statement JavaDoc stmt = conn.createStatement();
78     ResultSet JavaDoc 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