KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > ce > auction > persistence > HibernateFilterLong


1 package org.hibernate.ce.auction.persistence;
2
3 import org.hibernate.Session;
4 import org.apache.commons.logging.*;
5
6 import javax.servlet.*;
7 import javax.servlet.http.*;
8 import java.io.IOException JavaDoc;
9
10 /**
11  * A servlet filter that disconnects and reconnects a Hibernate Session for each request.
12  * <p>
13  * Use this filter for the <b>session-per-application-transaction</b> pattern
14  * with a <i>Long Session</i>. Don't forget to demarcate application transactions
15  * in your code, as described in Hibernate in Action.
16  *
17  * @see HibernateUtil
18  * @author Christian Bauer <christian@hibernate.org>
19  */

20 public class HibernateFilterLong
21         implements Filter {
22
23     private static final String JavaDoc HTTPSESSIONKEY = "HibernateSession";
24     private static Log log = LogFactory.getLog(HibernateFilterLong.class);
25
26     public void init(FilterConfig filterConfig) throws ServletException {
27         log.info("Servlet filter init, now disconnecting/reconnecting a Session for each request.");
28     }
29
30     public void doFilter(ServletRequest request,
31                          ServletResponse response,
32                          FilterChain chain)
33             throws IOException JavaDoc, ServletException {
34
35         // Try to get a Hibernate Session from the HttpSession
36
HttpSession userSession =
37                 ((HttpServletRequest) request).getSession();
38         Session hibernateSession =
39                 (Session) userSession.getAttribute(HTTPSESSIONKEY);
40
41         if (hibernateSession != null)
42             HibernateUtil.reconnect(hibernateSession);
43
44         // If there is no Session, the first call to
45
// HibernateUtil.beginTransaction in application code will open
46
// a new Session for this thread.
47
try {
48             chain.doFilter(request, response);
49
50             // Commit any pending database transaction.
51
HibernateUtil.commitTransaction();
52
53         } finally {
54             // TODO: The Session should be closed if a fatal exceptions occurs
55

56             // No matter what happens, disconnect the Session.
57
hibernateSession = HibernateUtil.disconnectSession();
58             // and store it in the users HttpSession
59
userSession.setAttribute(HTTPSESSIONKEY, hibernateSession);
60         }
61     }
62
63     public void destroy() {}
64
65 }
Popular Tags