1 package example.cmp.one2many; 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 ClientServlet extends HttpServlet { 19 StudentHome studentHome = null; 20 HouseHome houseHome = null; 21 22 23 26 public void init() 27 throws ServletException 28 { 29 try { 30 Context ejb = (Context)new InitialContext().lookup("java:comp/env/cmp"); 31 32 studentHome = (StudentHome)ejb.lookup("one2many_StudentBean"); 34 35 houseHome = (HouseHome)ejb.lookup("one2many_HouseBean"); 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 Collection students = null; 55 try { 56 students = studentHome.findAll(); 57 } catch(javax.ejb.FinderException e) { 58 throw new ServletException(e); 59 } 60 61 out.println("<h3>Student House assignments</h3>"); 62 63 Iterator iter = students.iterator(); 64 while (iter.hasNext()) { 65 Student student = (Student) iter.next(); 66 String name = student.getName(); 67 String houseName = student.getHouse().getName(); 68 out.println(name + " lives in " + houseName + "<br>"); 69 } 70 71 out.println("<h3>Residents of all Houses</h3>"); 73 Collection houses = null; 74 try { 75 houses = houseHome.findAll(); 76 } catch(javax.ejb.FinderException e) { 77 throw new ServletException(e); 78 } 79 80 iter = houses.iterator(); 82 while (iter.hasNext()) { 83 House house = (House) iter.next(); 84 out.println("<h4>" + house.getName() + "</h4>"); 85 86 students = (Collection) house.getStudentList(); 87 88 Iterator studentIter = students.iterator(); 90 if (! studentIter.hasNext()) 91 out.println("No students.<br>"); 92 93 while (studentIter.hasNext()) { 94 Student student = (Student) studentIter.next(); 95 out.println("<li>" + student.getName()); 96 } 97 } 98 99 134 } 135 } 136 | Popular Tags |