1 package example.cmp.create; 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 import java.io.PrintWriter; 11 12 15 public class CreateServlet extends HttpServlet { 16 17 private CourseHome _home = null; 18 19 22 public void setCourseHome(CourseHome home) 23 { 24 _home = home; 25 } 26 27 30 public void init() 31 throws ServletException 32 { 33 if (_home == null) { 34 try { 35 Context ic = new InitialContext(); 36 37 _home = (CourseHome) ic.lookup("java:comp/env/cmp/create_CourseBean"); 39 } catch (NamingException e) { 40 throw new ServletException(e); 41 } 42 } 43 } 44 45 public void service(HttpServletRequest req, HttpServletResponse res) 46 throws java.io.IOException, ServletException 47 { 48 PrintWriter out = res.getWriter(); 49 50 res.setContentType("text/html"); 51 52 out.println("<h3>Original classes</h3>"); 53 54 try { 55 Collection c = _home.findAll(); 56 Iterator iter = c.iterator(); 57 58 while (iter.hasNext()) { 59 Course course = (Course) iter.next(); 60 61 out.println(course.getCourseId() + " is taught by " + 62 course.getInstructor() + "<br>"); 63 } 64 } catch (FinderException e) { 65 throw new ServletException(e); 66 } 67 68 Course divination = null; 75 Course creatures = null; 76 77 try { 78 out.println("<h3>Adding some classes</h3>"); 79 80 90 divination = _home.create("Divination", "Sybil Trelawney"); 91 creatures = _home.create("Care of Magical Creatures", "Rubeus Hagrid"); 92 93 Collection c = _home.findAll(); 94 Iterator iter = c.iterator(); 95 96 while (iter.hasNext()) { 97 Course course = (Course) iter.next(); 98 99 out.println(course.getCourseId() + " is taught by " + 100 course.getInstructor() + "<br>"); 101 } 102 } 103 catch (Exception e) { 104 throw new ServletException(e); 105 } 106 107 out.println("<h3>Removing the new classes</h3>"); 108 109 try { 110 if (divination != null) 111 divination.remove(); 112 if (creatures != null) 113 creatures.remove(); 114 115 Collection c = _home.findAll(); 116 Iterator iter = c.iterator(); 117 118 while (iter.hasNext()) { 119 Course course = (Course) iter.next(); 120 121 out.println(course.getCourseId() + " is taught by " + 122 course.getInstructor() + "<br>"); 123 } 124 } catch (Exception e) { 125 throw new ServletException(e); 126 } 127 } 128 } 129 | Popular Tags |