KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > cmp > many2many > FindServlet


1 package example.cmp.many2many;
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  * A client to illustrate EJB managed relations in a many-to-many context.
17  */

18 public class FindServlet extends HttpServlet {
19   StudentHome studentHome;
20   CourseHome courseHome;
21
22   public void init()
23     throws ServletException
24   {
25     // obtain references to the home interfaces
26
try {
27       Context ejb = (Context)new InitialContext().lookup("java:comp/env/cmp");
28
29       // get the Student CMP-Bean home interface
30
studentHome = (StudentHome) ejb.lookup("many2many_StudentBean");
31
32       // get the Course CMP-Bean home interface
33
courseHome = (CourseHome) ejb.lookup("many2many_CourseBean");
34
35     } catch (NamingException e) {
36       throw new ServletException(e);
37     }
38   }
39
40   public void service(HttpServletRequest req, HttpServletResponse res)
41     throws java.io.IOException, ServletException
42   {
43     res.setContentType("text/html");
44
45     PrintWriter out = res.getWriter();
46
47     // get references to all entities we will work with
48
String studentName = "Hermione Granger";
49     String courseName = "Divination";
50
51     try {
52       // one student can be enrolled in any number of courses...
53
out.println("<h3>" + studentName + "'s classes:</h3>");
54
55       // Show all courses the student is currently enrolled in
56
Iterator it = courseHome.findByStudent(studentName).iterator();
57       if (! it.hasNext())
58         out.println("No classes");
59
60       while (it.hasNext())
61         out.println("<li>" + ((Course) it.next()).getName());
62
63     // ...and a course can be taught to any number of students
64
out.println("<h3>" + courseName + " students:</h3>");
65       it = studentHome.findByCourse(courseName).iterator();
66       if (! it.hasNext())
67         out.println("No students");
68
69       while (it.hasNext())
70         out.println("<li>" + ((Student)it.next()).getName() );
71     } catch (FinderException e) {
72       throw new ServletException(e);
73     }
74   }
75 }
76
Popular Tags