01: package example;
02:
03: import java.io.*;
04:
05: import javax.servlet.*;
06: import javax.servlet.http.*;
07:
08: import javax.naming.InitialContext;
09: import javax.naming.Context;
10:
11: /**
12: * Implementation of the test servlet.
13: */
14: public class TestServlet extends HttpServlet {
15: // Reference to the factory
16: private ConnectionFactoryImpl _factory;
17:
18: /**
19: * <code>init()</code> stores the factory for efficiency since JNDI
20: * is relatively slow.
21: */
22: public void init() throws ServletException {
23: try {
24: Context ic = new InitialContext();
25:
26: _factory = (ConnectionFactoryImpl) ic
27: .lookup("java:comp/env/factory");
28: } catch (Exception e) {
29: throw new ServletException(e);
30: }
31: }
32:
33: /**
34: * Use the connection. All JCA connections must use the following
35: * pattern to ensure the connection is closed even when exceptions
36: * occur.
37: */
38: public void service(HttpServletRequest request,
39: HttpServletResponse response) throws IOException,
40: ServletException {
41: response.setContentType("text/html");
42: PrintWriter out = response.getWriter();
43:
44: ConnectionImpl conn = null;
45:
46: try {
47: out.println("Factory: " + _factory + "<br>");
48:
49: conn = _factory.getConnection();
50:
51: out.println("Connection: " + conn + "<br>");
52: } catch (Exception e) {
53: throw new ServletException(e);
54: } finally {
55: // it is very important to put this close in the finally block
56: if (conn != null)
57: conn.close();
58: }
59: }
60: }
|