01: package example;
02:
03: import java.io.PrintWriter;
04: import java.io.IOException;
05:
06: import java.util.List;
07:
08: import javax.annotation.*;
09:
10: import javax.servlet.ServletException;
11:
12: import javax.servlet.http.HttpServlet;
13: import javax.servlet.http.HttpServletRequest;
14: import javax.servlet.http.HttpServletResponse;
15:
16: import javax.transaction.*;
17: import javax.persistence.*;
18: import javax.webbeans.In;
19:
20: /**
21: * The CourseServlet queries the active courses and displays them.
22: */
23: public class CourseServlet extends HttpServlet {
24: @In
25: private UserTransaction _uTrans;
26:
27: @In
28: private EntityManager _manager;
29:
30: /**
31: * Initializes the database for the example.
32: */
33: public void init() throws ServletException {
34: Course course = null;
35:
36: try {
37: course = _manager.find(Course.class, new Integer(1));
38: if (course != null)
39: return;
40: } catch (Exception e) {
41: }
42:
43: _manager.getTransaction().begin();
44: try {
45: _manager.persist(new Course("Potions", "Severus Snape"));
46: _manager.persist(new Course("Transfiguration",
47: "Minerva McGonagall"));
48: } finally {
49: _manager.getTransaction().commit();
50: }
51: }
52:
53: /**
54: * Illustrates how to interact with the Course EJB
55: */
56: public void service(HttpServletRequest req, HttpServletResponse res)
57: throws java.io.IOException, ServletException {
58: PrintWriter out = res.getWriter();
59:
60: res.setContentType("text/html");
61:
62: out.println("<h3>Course Details</h3>");
63:
64: Query query = _manager.createQuery("SELECT o FROM Course o");
65:
66: for (Course course : (List<Course>) query.getResultList()) {
67: out.println("course: " + course.course() + "<br>");
68: out.println("teacher: " + course.teacher() + "<br>");
69: out.println("<br>");
70: }
71:
72: out.println("<h3>Add a Course</h3>");
73:
74: Course newCourse = new Course("Charms", "Professor Flitwick");
75:
76: _manager.getTransaction().begin();
77: try {
78: _manager.persist(newCourse);
79: } finally {
80: _manager.getTransaction().commit();
81: }
82:
83: for (Course course : (List<Course>) query.getResultList()) {
84: out.println("course: " + course.course() + "<br>");
85: out.println("teacher: " + course.teacher() + "<br>");
86: out.println("<br>");
87: }
88:
89: _manager.getTransaction().begin();
90: try {
91: Course course = _manager.find(Course.class, newCourse
92: .getId());
93:
94: _manager.remove(course);
95: } finally {
96: _manager.getTransaction().commit();
97: }
98: }
99: }
|