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 CollectionServlet extends HttpServlet { 19 StudentHome studentHome; 20 CourseHome courseHome; 21 22 25 public void init() 26 throws ServletException 27 { 28 try { 30 Context ejb = (Context)new InitialContext().lookup("java:comp/env/cmp"); 31 32 studentHome = (StudentHome) ejb.lookup("many2many_StudentBean"); 34 35 courseHome = (CourseHome) ejb.lookup("many2many_CourseBean"); 37 38 } catch (NamingException e) { 39 throw new ServletException(e); 40 } 41 } 42 43 46 public void service(HttpServletRequest req, HttpServletResponse res) 47 throws java.io.IOException, ServletException 48 { 49 res.setContentType("text/html"); 50 51 PrintWriter out = res.getWriter(); 52 53 Student student = null; 55 Course course = null; 56 try { 57 student = studentHome.findByPrimaryKey("Hermione Granger"); 58 course = courseHome.findByPrimaryKey("Divination"); 59 } catch (javax.ejb.FinderException e) { 60 throw new ServletException(e); 61 } 62 63 out.println("<h3>" + student.getName() + "'s classes:</h3>"); 65 66 Iterator it = student.getCourseList().iterator(); 68 while (it.hasNext()) 69 out.println("<li> " + ((Course) it.next()).getName() ); 70 71 out.println("<p>Enrolling " + student.getName() + " in " + 73 course.getName() + "\n"); 74 75 student.addCourse(course); 76 77 out.println("<h3>" + student.getName() + "'s new classes:</h3>"); 79 it = student.getCourseList().iterator(); 80 while (it.hasNext()) 81 out.println("<li> " + ((Course) it.next()).getName() ); 82 83 student.removeCourse(course); 84 85 out.println("<h3>" + course.getName() + " students:</h3>"); 87 88 it = course.getStudentList().iterator(); 90 while (it.hasNext()) 91 out.println("<li> " + ((Student) it.next()).getName()); 92 93 out.println("<p>Enrolling " + student.getName() + " in " + 95 course.getName()); 96 97 98 course.addStudent(student); 99 100 out.println("<h3>" + course.getName() + " new students:</h3>"); 102 103 it = course.getStudentList().iterator(); 105 while (it.hasNext()) 106 out.println("<li> " + ((Student) it.next()).getName()); 107 108 course.removeStudent(student); 110 } 111 } 112 | Popular Tags |