1.4.2. 处理与渲染

我们来实现处理请求以及渲染页面的工作。

  1. // Write HTML header
  2. PrintWriter out = response.getWriter();
  3. out.println("<html><head><title>Event Manager</title></head><body>");
  4. // Handle actions
  5. if ( "store".equals(request.getParameter("action")) ) {
  6. String eventTitle = request.getParameter("eventTitle");
  7. String eventDate = request.getParameter("eventDate");
  8. if ( "".equals(eventTitle) || "".equals(eventDate) ) {
  9. out.println("<b><i>Please enter event title and date.</i></b>");
  10. } else {
  11. createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));
  12. out.println("<b><i>Added event.</i></b>");
  13. }
  14. }
  15. // Print page
  16. printEventForm(out);
  17. listEvents(out, dateFormatter);
  18. // Write HTML footer
  19. out.println("</body></html>");
  20. out.flush();
  21. out.close();

listEvents()方法使用绑定到当前线程的Hibernate Session来执行查询:

  1. private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) {
  2. List result = HibernateUtil.getSessionFactory()
  3. .getCurrentSession().createCriteria(Event.class).list();
  4. if (result.size() > 0) {
  5. out.println("<h2>Events in database:</h2>");
  6. out.println("<table border='1'>");
  7. out.println("<tr>");
  8. out.println("<th>Event title</th>");
  9. out.println("<th>Event date</th>");
  10. out.println("</tr>");
  11. for (Iterator it = result.iterator(); it.hasNext();) {
  12. Event event = (Event) it.next();
  13. out.println("<tr>");
  14. out.println("<td>" + event.getTitle() + "</td>");
  15. out.println("<td>" + dateFormatter.format(event.getDate()) + "</td>");
  16. out.println("</tr>");
  17. }
  18. out.println("</table>");
  19. }
  20. }

最后,store动作会被导向到createAndStoreEvent()方法,它也使用当前线程的Session:

  1. protected void createAndStoreEvent(String title, Date theDate) {
  2. Event theEvent = new Event();
  3. theEvent.setTitle(title);
  4. theEvent.setDate(theDate);
  5. HibernateUtil.getSessionFactory()
  6. .getCurrentSession().save(theEvent);
  7. }

大功告成,这个servlet写完了。Hibernate会在单一的SessionTransaction中处理到达的servlet请求。如同在前面的独立应用程序中那样,Hibernate可以自动的把这些对象绑定到当前运行的线程中。这给了你用任何你喜欢的方式来对代码分层及访问SessionFactory的自由。通常,你会用更加完备的设计,把数据访问代码转移到数据访问对象中(DAO模式)。请参见Hibernate Wiki,那里有更多的例子。