KickJava   Java API By Example, From Geeks To Geeks.

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


1 package example.cmp.one2one;
2
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5
6 import javax.ejb.*;
7
8 import javax.naming.*;
9
10 import java.util.Collection;
11 import java.util.Iterator;
12
13 import java.io.PrintWriter;
14
15 /**
16  * Illustrates a client that makes use of the 1-1 related CMP beans.
17  */

18 public class ClientServlet extends HttpServlet {
19   private TeacherHome _teacherHome = null;
20   private CourseHome _courseHome = null;
21
22   /**
23    * Sets the TeacherHome.
24    */

25   public void setTeacherHome(TeacherHome teacherHome)
26   {
27     _teacherHome = teacherHome;
28   }
29
30   /**
31    * Sets the CourseHome.
32    */

33   public void setCourseHome(CourseHome courseHome)
34   {
35     _courseHome = courseHome;
36   }
37
38   /**
39    * Initialize the servlet.
40    */

41   public void init()
42     throws ServletException
43   {
44     try {
45       Context ic = new InitialContext();
46       
47       Context cmp = (Context) ic.lookup("java:comp/env/cmp");
48
49       // get the Teacher CMP-Bean home interface
50
if (_teacherHome == null)
51         _teacherHome = (TeacherHome) cmp.lookup("one2one_teachers");
52
53       // get the Course CMP-Bean home interface
54
if (_courseHome == null)
55         _courseHome = (CourseHome) cmp.lookup("one2one_courses");
56     } catch (NamingException e) {
57       throw new ServletException(e);
58     }
59   }
60   /**
61    *
62    */

63   public void service(HttpServletRequest req, HttpServletResponse res)
64     throws java.io.IOException, ServletException
65   {
66     res.setContentType("text/html");
67
68     PrintWriter out = res.getWriter();
69
70     try {
71       Iterator iter = _courseHome.findAll().iterator();
72
73       out.println("<H3>Getting Teacher-Course Assignments</H3>");
74
75       while (iter.hasNext()) {
76         Course course = (Course) iter.next();
77         out.println(course.getTeacher().getName() + " teaches " +
78                     course.getName() + "<br>");
79       }
80     } catch (FinderException fe) {
81       throw new ServletException(fe);
82     }
83   }
84 }
85
Popular Tags