1 package example.cmp.basic; 2 3 import javax.servlet.*; 4 import javax.servlet.http.*; 5 6 import javax.naming.*; 7 import javax.transaction.*; 8 import javax.ejb.*; 9 10 import java.util.*; 11 import java.io.PrintWriter; 12 13 16 public class CourseServlet extends HttpServlet { 17 22 private CourseHome _home = null; 23 32 private UserTransaction _userTrans = null; 33 34 37 public void setCourseHome(CourseHome home) 38 { 39 _home = home; 40 } 41 42 45 public void init() 46 throws ServletException 47 { 48 try { 49 Context ic = new InitialContext(); 50 51 Context cmp = (Context) ic.lookup("java:comp/env/cmp"); 53 54 if (cmp == null) 55 throw new ServletException("ejb-server has not initialized properly."); 56 57 if (_home == null) 62 _home = (CourseHome) cmp.lookup("basic_CourseBean"); 63 64 Object trans = ic.lookup("java:comp/UserTransaction"); 66 _userTrans = (UserTransaction) trans; 67 } catch (NamingException e) { 68 throw new ServletException(e); 69 } 70 } 71 72 75 public void service(HttpServletRequest req, HttpServletResponse res) 76 throws java.io.IOException, ServletException 77 { 78 PrintWriter out = res.getWriter(); 79 80 res.setContentType("text/html"); 81 82 Course []course = new Course[2]; 92 93 try { 94 course[0] = _home.findByPrimaryKey("Potions"); 95 course[1] = _home.findByPrimaryKey("Transfiguration"); 96 97 out.println("<h3>Course Details</h3>"); 98 99 for (int i = 0; i < course.length; i++) { 100 out.println("course: " + course[i].getId() + "<br>"); 101 out.println("instructor: " + course[i].getInstructor() + "<br>"); 102 out.println("<br>"); 103 } 104 105 out.println(); 106 out.println("<p>Swap the instructors for the two courses." ); 107 out.println("The change will be automatically and instantly reflected" ); 108 out.println("in the database" ); 109 out.println(); 110 111 114 course[0].swap(course[1]); 115 116 out.println("<h3>New Course Details:</h3>"); 117 for (int i = 0; i < course.length; i++) { 118 out.println("course: " + course[i].getId() + "<br>"); 119 out.println("instructor: " + course[i].getInstructor() + "<br>"); 120 out.println("<br>"); 121 } 122 123 try { 129 _userTrans.begin(); 130 String temp = course[0].getInstructor(); 131 course[0].setInstructor(course[1].getInstructor()); 132 course[1].setInstructor(temp); 133 } finally { 134 _userTrans.commit(); 135 } 136 } 137 catch (Exception e) { 138 throw new ServletException(e); 139 } 140 } 141 } 142 | Popular Tags |