Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

10.4. Integrating Struts with Hibernate

Problem

You want to use Hibernate for object/relational mapping in your Struts application.

Solution

Use a servlet filter such as the Persistence class shown in Example 10-11.

Example 10-11. Servlet filter for Hibernate sessions

package com.jadecove.util; import java.io.*; import javax.servlet.*; import net.sf.hibernate.*; import net.sf.hibernate.cfg.Configuration; /** * Filter which manages a ThreadLocal hibernate session. Obtain the session * by calling Persistance.getSession( ). */ public class Persistence implements Filter { /** * Holds the current hibernate session, if one has been created. */ protected static ThreadLocal hibernateHolder = new ThreadLocal( ); protected static SessionFactory factory; public void init(FilterConfig filterConfig) throws ServletException { // Initialize hibernate try { doInit( ); } catch (HibernateException ex) { throw new ServletException(ex); } } /** * This method should only be called when this class is used directly - * that is, when using this class outside of the servlet container. * @throws HibernateException */ public static void doInit( ) throws HibernateException { factory = new Configuration( ).configure( ).buildSessionFactory( ); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (hibernateHolder.get( ) != null) throw new IllegalStateException( "A session is already associated with this thread! " + "Someone must have ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page