I am now the owner of a Struts-1 application, and the Hibernate session management is all over the place. I have searched online documentation but have not found a clear explanation of the best way to manage Hibernate sessions in a Struts application. Presumably a Hibernate Session should be created (or fetched) at the start of each action, and a transaction opened, and then the transaction committed or rolled back at the end of the action. Is that correct? How can this be managed for all actions without duplicating code in each action? Should each Action fetch objects from the DB, call model functions, and then save the objects, ala Ruby on Rails?


I don't think struts 1 ships with an OpenSessionInView filter, but one way to manage sessions is opening sessions on a per-request basis, which are then accessed via the thread local pattern.

This will keep the session open until the request is done rendering, meaning you can use lazily instantiated collections in your views safely.

Spring ships with an opensessioninview filter, here is an article on how to use it, or, it's relatively straightforward to write your own as a standard servlet filter.

to write your own, you would write ServletFilter that implements Filter, and implement a doFilter method. it would look something like:

void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) {
   Session session;
   try {
      session = // get my hibernate session here
      // do the request
      chain.doFilter(req, res);
   } catch (Whatever) {
   } finally {
     // close my session here

you would need to register this filter in your web.xml, and apply it to the URLs that you need sessions with. This is not the most elegant solution in the world, but it does work just fine.

  • Thanks. I would rather not get involved with Spring if I don't have to. Can you elaborate on the "straightforward to write your own" part? I've read on article suggesting the same, but coming from RoR I didn't find it straightforward at all. – kevin cline Jun 13 '11 at 15:38
  • 1
    I added an example, hope it helps. a lot of the java servlet stuff is going to seem really ugly if you're coming from a rails background :(. – Paul Sanwald Jun 13 '11 at 20:21
  • Thanks!!! I will try it. It IS ugly. I'm seriously thinking of migrating the whole thing to Grails page by page; we need to move all the pages to Javascript + Ajax anyway. – kevin cline Jun 14 '11 at 22:44
  • kevin, that would certainly make it easier to maintain. hope this filter works for you in the short term, it should do the trick. – Paul Sanwald Jun 15 '11 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.