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 18 public class FindServlet extends HttpServlet { 19 StudentHome studentHome; 20 CourseHome courseHome; 21 22 public void init() 23 throws ServletException 24 { 25 try { 27 Context ejb = (Context)new InitialContext().lookup("java:comp/env/cmp"); 28 29 studentHome = (StudentHome) ejb.lookup("many2many_StudentBean"); 31 32 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 String studentName = "Hermione Granger"; 49 String courseName = "Divination"; 50 51 try { 52 out.println("<h3>" + studentName + "'s classes:</h3>"); 54 55 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 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 |