1 package example; 2 3 import java.io.PrintWriter ; 4 import java.io.IOException ; 5 6 import javax.servlet.ServletException ; 7 8 import javax.servlet.http.HttpServlet ; 9 import javax.servlet.http.HttpServletRequest ; 10 import javax.servlet.http.HttpServletResponse ; 11 12 import javax.persistence.EntityManager; 13 import javax.persistence.PersistenceContext; 14 15 18 public class CourseServlet extends HttpServlet { 19 @PersistenceContext(name="example") 20 private EntityManager _manager; 21 22 25 public void init() 26 throws ServletException 27 { 28 CourseBean course = null; 29 30 try { 31 course = _manager.find(CourseBean.class, new Integer (1)); 32 if (course != null) 33 return; 34 } catch (Exception 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 58 public void service(HttpServletRequest req, HttpServletResponse res) 59 throws java.io.IOException , ServletException 60 { 61 PrintWriter 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 (1)); 68 course[1] = _manager.find(CourseBean.class, new Integer (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 |