KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.hibernate.ce.auction.persistence;
2
3 import org.apache.commons.logging.*;
4
5 import javax.servlet.*;
6 import java.io.IOException JavaDoc;
7
8 /**
9  * A servlet filter that opens and closes a Hibernate Session for each request.
10  * <p>
11  * This filter guarantees a sane state, committing any pending database
12  * transaction once all other filters (and servlets) have executed. It also
13  * guarantees that the Hibernate <tt>Session</tt> of the current thread will
14  * be closed before the response is send to the client.
15  * <p>
16  * Use this filter for the <b>session-per-request</b> pattern and if you are
17  * using <i>Detached Objects</i>.
18  *
19  * @see HibernateUtil
20  * @author Christian Bauer <christian@hibernate.org>
21  */

22 public class HibernateFilter implements Filter {
23
24     private static Log log = LogFactory.getLog(HibernateFilter.class);
25
26     public void init(FilterConfig filterConfig) throws ServletException {
27         log.info("Servlet filter init, now opening/closing 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         // There is actually no explicit "opening" of a Session, the
36
// first call to HibernateUtil.beginTransaction() in control
37
// logic (e.g. use case controller/event handler) will get
38
// a fresh Session.
39
try {
40             chain.doFilter(request, response);
41
42             // Commit any pending database transaction.
43
HibernateUtil.commitTransaction();
44
45         } finally {
46
47             // No matter what happens, close the Session.
48
HibernateUtil.closeSession();
49
50         }
51     }
52
53     public void destroy() {}
54
55 }
Popular Tags