1 package example; 2 3 import javax.servlet.*; 4 import javax.servlet.http.*; 5 6 import javax.naming.*; 7 import javax.ejb.*; 8 9 import java.util.*; 10 11 import java.io.PrintWriter; 12 13 25 public class FindServlet extends HttpServlet { 26 30 private CourseHome _home = null; 31 32 35 public void setCourseHome(CourseHome home) 36 { 37 _home = home; 38 } 39 40 49 public void init() 50 throws ServletException 51 { 52 if (_home == null) { 53 try { 54 Context ic = new InitialContext(); 55 56 _home = (CourseHome) ic.lookup("java:comp/env/cmp/find"); 58 } catch (NamingException e) { 59 throw new ServletException(e); 60 } 61 } 62 } 63 64 67 public void service(HttpServletRequest req, HttpServletResponse res) 68 throws java.io.IOException, ServletException 69 { 70 PrintWriter out = res.getWriter(); 71 72 res.setContentType("text/html"); 73 74 out.println("<h3>Find by Primary Key</h3>"); 75 76 String courseName = "Potions"; 78 79 try { 80 85 Course course = _home.findByPrimaryKey(courseName); 86 87 out.println(course.getId() + " is taught by " + 88 course.getInstructor()); 89 } catch (ObjectNotFoundException e) { 90 out.println("There is no course '" + courseName + "'"); 91 } catch (FinderException e) { 92 throw new ServletException(e); 93 } 94 95 out.println("<h3>Find All Courses</h3>"); 96 97 try { 98 101 Collection c = _home.findAll(); 102 Iterator iter = c.iterator(); 103 104 108 if (! iter.hasNext()) 109 out.println("No classes are being taught!"); 110 111 while (iter.hasNext()) { 113 Course course = (Course) iter.next(); 114 115 out.println(course.getId() + " is taught by " + 116 course.getInstructor() + "<br>"); 117 } 118 } catch (ObjectNotFoundException e) { 119 throw new ServletException(e); 120 } catch (FinderException e) { 121 throw new ServletException(e); 122 } 123 124 out.println("<h3>Find the course taught by an instructor</h3>"); 125 126 String teacher = "Remus Lupin"; 127 try { 128 132 Course course = _home.findByInstructor(teacher); 133 134 137 out.println(course.getId() + " is taught by " + 139 course.getInstructor() + "<br>"); 140 } catch (ObjectNotFoundException e) { 141 out.println(teacher + " is not teaching any courses."); 142 } catch (FinderException e) { 143 throw new ServletException(e); 144 } 145 } 146 } 147 | Popular Tags |