private static final String PARAM_USE_PROXY = "HIBERNATE_FILTER_USE_PROXY";
private boolean useProxy = true;
public void doFilter(ServletRequest request, ServletResponse aResponse, FilterChain aChain)
throws IOException, ServletException {
Session session = null;
boolean sessionWasCreated = false;
try {
// We will try to get the Hiberate Session from the request. If
// it doesn't exist, then we will create it, otherwise
// we will use the one that already exists.
session = (Session)request.getAttribute(SESSION_ATTRIBUTE_KEY);
if (session == null) {
SessionFactory sessionFactory = GlobalSessionFactory.get();
if (useProxy) {
session = SessionProxy.createProxy(this, sessionFactory);
} else {
session = sessionFactory.openSession();
if (log.isDebugEnabled()) {
log.debug("Session opened: "+session);
}
}
request.setAttribute(SESSION_ATTRIBUTE_KEY, session);
ThreadSession.set(session);
sessionWasCreated = true;
log.debug("Session created: "+session);
} else {
log.debug("Reusing session from request: "+session);
}
} catch (Exception exc) {
log.error("Error opening Hibernate session.", exc);
}
try {
aChain.doFilter(request, aResponse);
} finally {
try {
if (sessionWasCreated) {
if (session != null) {
// Only try to close the connection if it is open,
// since it might have been closed somewhere else
// by mistake.
if (session.isOpen()) {
session.close();
if (log.isDebugEnabled()) {
log.debug("Session closed: "+session);
}
} else {
log.debug("Session already closed: "+session);