KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > CourseServlet


1 package example;
2
3 import java.io.PrintWriter JavaDoc;
4 import java.io.IOException JavaDoc;
5
6 import javax.servlet.ServletException JavaDoc;
7
8 import javax.servlet.http.HttpServlet JavaDoc;
9 import javax.servlet.http.HttpServletRequest JavaDoc;
10 import javax.servlet.http.HttpServletResponse JavaDoc;
11
12 import javax.persistence.EntityManager;
13 import javax.persistence.PersistenceContext;
14
15 /**
16  * The basic CourseClient shows the basic flow of any Resin-CMP client.
17  */

18 public class CourseServlet extends HttpServlet JavaDoc {
19   @PersistenceContext(name="example")
20   private EntityManager _manager;
21
22   /**
23    * Illustrates how to interact with the Course EJB
24    */

25   public void init()
26     throws ServletException JavaDoc
27   {
28     CourseBean course = null;
29     
30     try {
31       course = _manager.find(CourseBean.class, new Integer JavaDoc(1));
32       if (course != null)
33     return;
34     } catch (Exception JavaDoc e) {
35     }
36
37     _manager.getTransaction().begin();
38     try {
39       CourseBean potions = new CourseBean();
40       potions.setCourse("Potions");
41       potions.setTeacher("Severus Snape");
42
43       _manager.persist(potions);
44
45       CourseBean xfig = new CourseBean();
46       xfig.setCourse("Transfiguration");
47       xfig.setTeacher("Minerva McGonagall");
48
49       _manager.persist(xfig);
50     } finally {
51       _manager.getTransaction().commit();
52     }
53   }
54
55   /**
56    * Illustrates how to interact with the Course Bean.
57    */

58   public void service(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
59     throws java.io.IOException JavaDoc, ServletException JavaDoc
60   {
61     PrintWriter JavaDoc out = res.getWriter();
62
63     res.setContentType("text/html");
64
65     CourseBean []course = new CourseBean[2];
66
67     course[0] = _manager.find(CourseBean.class, new Integer JavaDoc(1));
68     course[1] = _manager.find(CourseBean.class, new Integer JavaDoc(2));
69
70     out.println("<h3>Course Details</h3>");
71
72     for (int i = 0; i < course.length; i++) {
73       out.println("course: " + course[i].getCourse() + "<br>");
74       out.println("teacher: " + course[i].getTeacher() + "<br>");
75       out.println("<br>");
76     }
77   }
78 }
79
Popular Tags