KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > cmp > basic > InitServlet


1 package example.cmp.basic;
2
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5
6 import java.sql.*;
7 import javax.sql.*;
8
9 import java.util.*;
10 import java.io.PrintWriter;
11
12 /**
13  * The InitServlet initializes the database.
14  *
15  * Normally, this would be handled by CMP code, but in this case
16  * the example doesn't include the ejbCreate methods to make it simpler.
17  */

18 public class InitServlet extends HttpServlet {
19   /**
20    * The DataSource for the table.
21    */

22   private DataSource _ds = null;
23
24   /**
25    * Sets the data source.
26    */

27   public void setDataSource(DataSource ds)
28   {
29     _ds = ds;
30   }
31
32   /**
33    * Initializes the reference to the CourseBean home interface.
34    */

35   public void init()
36     throws ServletException
37   {
38     try {
39       if (_ds == null)
40     throw new ServletException("data-source must be specified");
41
42       Connection conn = _ds.getConnection();
43
44       try {
45     Statement stmt = conn.createStatement();
46
47     ResultSet rs = stmt.executeQuery("SELECT id FROM basic_courses");
48
49     if (rs.next()) {
50       rs.close();
51       stmt.close();
52       return; // already initialized
53
}
54
55     stmt.executeUpdate("INSERT INTO basic_courses VALUES ('Potions', 'Severus Snape')");
56     stmt.executeUpdate("INSERT INTO basic_courses VALUES ('Transfiguration', 'Minerva McGonagall')");
57
58     stmt.close();
59       } finally {
60     conn.close();
61       }
62     } catch (SQLException e) {
63       throw new ServletException(e);
64     }
65   }
66
67   /**
68    * Illustrates how to interact with the Course EJB
69    */

70   public void service(HttpServletRequest req, HttpServletResponse res)
71     throws java.io.IOException, ServletException
72   {
73     throw new UnsupportedOperationException();
74   }
75 }
76
Popular Tags