KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > HelloJndiServlet


1 package example;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5
6 import java.util.logging.Level;
7 import java.util.logging.Logger;
8
9 import javax.ejb.CreateException;
10
11 import javax.naming.Context;
12 import javax.naming.InitialContext;
13 import javax.naming.NamingException;
14
15 import javax.servlet.ServletConfig;
16 import javax.servlet.ServletException;
17 import javax.servlet.http.HttpServlet;
18 import javax.servlet.http.HttpServletRequest;
19 import javax.servlet.http.HttpServletResponse;
20
21 /**
22  * Client servlet that:
23  * <ol>
24  * <li>uses JNDI to get a HessianContextFactory
25  * <li>uses the factory to obtain a HelloHome
26  * <li>uses the HelloHome to create a Home stub
27  * <li>uses the Home stub to query a server about a greeting.
28  * </ol>
29  */

30 public class HelloJndiServlet extends HttpServlet {
31   static protected final Logger log =
32     Logger.getLogger(HelloJndiServlet.class.getName());
33
34   /**
35    * The servlet stores the Home after the initial lookup.
36    * Since the Home never changes, caching the lookup in
37    * a member variable saves some performance.
38    */

39   private HelloHome helloHome;
40
41   /**
42    * The init method looks up the HelloHome using JNDI and
43    * stores it in a member variable.
44    */

45   public void init(ServletConfig config)
46     throws ServletException
47   {
48     super.init(config);
49
50     /**
51      * Connect to the remote EJB server using JNDI and obtain a HomeHandle.
52      */

53     try {
54       Context ejb = (Context) new InitialContext().lookup("java:comp/env/ejb");
55
56       /*
57        * Look up the hello home. "hello" is the ejb-name
58        * in the deployment descriptor.
59        */

60       helloHome = (HelloHome) ejb.lookup("hello");
61
62     } catch (NamingException e) {
63       throw new ServletException("java:comp/env/ejb",e);
64     }
65   }
66
67   /**
68    * Call the hello method. The Hello stub is created using the
69    * create method of HelloHome.
70    *
71    * @param request the servlet request object.
72    * @param response the servlet response object.
73    */

74   public void doGet(HttpServletRequest request,
75                     HttpServletResponse response)
76     throws IOException, ServletException
77   {
78     try {
79       PrintWriter out = response.getWriter();
80
81       response.setContentType("text/html");
82
83       Hello hello = helloHome.create();
84
85       out.print("Message: ");
86       out.println(hello.hello());
87     } catch (CreateException e) {
88       throw new ServletException(e);
89     }
90   }
91 }
92
Popular Tags