KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > session > local > CounterServlet


1 package example.session.local;
2
3 import java.io.*;
4
5 import javax.ejb.*;
6 import javax.naming.*;
7 import javax.servlet.*;
8 import javax.servlet.http.*;
9
10 /**
11  * Client servlet querying a server about a greeting.
12  *
13  * <h3>JNDI client configuration</h3>
14  *
15  * <code><pre>
16  * &lt;jndi-link>
17  * &lt;jndi-name>java:comp/env/ejb&lt;/jndi-name>
18  * &lt;jndi-factory>com.caucho.ejb.BurlapContextFactory&lt;/jndi-factory>
19  * &lt;init-param java.naming.provider.url="http://localhost:8080/cmp/example"/>
20  * &lt;/jndi-link>
21  * </pre></code>
22  */

23 public class CounterServlet extends HttpServlet {
24   /**
25    * The servlet stores the home interface after the initial lookup.
26    * Since the home interface never changes, caching the lookup will save
27    * some performance.
28    */

29   private CounterHome counterHome;
30
31   /**
32    * The init method looks up the CounterHome interface using JNDI and
33    * stores it in a servlet variable.
34    */

35   public void init()
36     throws ServletException
37   {
38     try {
39       /*
40        * Look up the local EJB context using JNDI.
41        * The context contains the EJB beans in the local web-app
42        *
43        * Since we're using the remote interface, it uses ejb.
44        */

45       Context ejb = (Context) new InitialContext().lookup("java:comp/env/ejb");
46       /*
47        * Look up the counter home. "session-counter" is the ejb-name
48        * in the deployment descriptor.
49        */

50       counterHome = (CounterHome) ejb.lookup("session-counter");
51     } catch (Exception e) {
52       throw new ServletException(e);
53     }
54   }
55
56   /**
57    * Calls the counter twice. Since it's a stateful session bean, the
58    * counter is new for each call.
59    *
60    * @param request the servlet request object.
61    * @param response the servlet response object.
62    */

63   public void doGet(HttpServletRequest request,
64                     HttpServletResponse response)
65     throws IOException, ServletException
66   {
67     try {
68       PrintWriter out = response.getWriter();
69
70       response.setContentType("text/html");
71
72       Counter counter = counterHome.create();
73
74       out.print("Count: ");
75       out.print(counter.hit());
76       out.println("<br>");
77       
78       out.print("Count: ");
79       out.print(counter.hit());
80       out.println("<br>");
81     } catch (CreateException e) {
82       throw new ServletException(e);
83     }
84   }
85 }
86
Popular Tags