KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > cmp > select > ClientServlet


1 package example.cmp.select;
2
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5
6 import javax.naming.*;
7 import javax.ejb.*;
8
9 import java.util.*;
10
11 import java.io.PrintWriter;
12
13 /**
14  * A client to illustrate entity bean select methods. Because select
15  * methods aren't directly usable by clients, the beans need to
16  * create business methods to return the selected values.
17  */

18 public class ClientServlet extends HttpServlet {
19
20   private StudentHome _studentHome = null;
21   private HouseHome _houseHome = null;
22
23   /**
24    * Sets the EJB student home.
25    */

26   public void setStudentHome(StudentHome home)
27   {
28     _studentHome = home;
29   }
30
31   /**
32    * Sets the EJB house home.
33    */

34   public void setHouseHome(HouseHome home)
35   {
36     _houseHome = home;
37   }
38
39   public void init()
40     throws ServletException
41   {
42     try {
43       // The initial context
44
Context ic = new InitialContext();
45       // The JNDI context containing local EJB homes
46
Context cmp = (Context) ic.lookup("java:comp/env/cmp");
47
48       // get the house stub
49
if (_houseHome == null)
50         _houseHome = (HouseHome) cmp.lookup("select_house");
51       if (_studentHome == null)
52         _studentHome = (StudentHome) cmp.lookup("select_student");
53
54     } catch (NamingException ne) {
55       throw new ServletException(ne);
56     }
57
58   }
59
60   public void service(HttpServletRequest req, HttpServletResponse res)
61     throws java.io.IOException, ServletException
62   {
63     res.setContentType("text/html");
64
65     PrintWriter out = res.getWriter();
66
67     Iterator iterHouses = null;
68     try {
69       Collection houses = _houseHome.findAll();
70       iterHouses = houses.iterator();
71     }
72     catch (FinderException fe) {
73       throw new ServletException(fe);
74     }
75
76     // iterate through all Houses
77
while (iterHouses.hasNext()) {
78       House house = (House) iterHouses.next();
79       out.println("<H3>Boys living in " + house.getName() + ":</H3>");
80
81       // Iterate through the sorted student names
82
ListIterator boys = house.getAllBoyNamesSorted().listIterator();
83       
84       if (! boys.hasNext())
85         out.println("No boys are living in " + house.getName());
86       else {
87         while (boys.hasNext())
88           out.println(boys.next() + "<BR>");
89       }
90
91       out.println("<BR>");
92     }
93   }
94 }
95
Popular Tags