Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials:
 

Software Solutions and Services
 

 
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
 
Developing Struts Hibernate Plugin 
 

In this section we will develop java code for Struts Hibernate Plugin.

 

Developing Struts Hibernate Plugin

                         

In this section we will develop java code for Struts Hibernate Plugin. Our Hibernate Plugin will create Hibernate Session factory and cache it in the servlet context. This strategy enhances the performance of the application.

Source Code Of Hibernate Struts Plugin:

 

 

 

 

 

package roseindia.net.plugin;

import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;


public class HibernatePlugIn implements PlugIn {
   private String _configFilePath = "/hibernate.cfg.xml";

    /**
     * the key under which the <code>SessionFactory </code> instance is stored
     * in the <code>ServletContext</code>.
     */
    public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName();

  private SessionFactory _factory = null;

   public void destroy() {
     try{
       _factory.close();
     }catch(HibernateException e){
      System.out.println("Unable to close Hibernate Session Factory: " + e.getMessage());
     }
       
   }

   public void init(ActionServlet servlet, 
ModuleConfig config
throws ServletException {
     System.out.println("*************************************");
   System.out.println("**** Initilizing HibernatePlugIn   **********");
        Configuration configuration = null;
        URL configFileURL = null;
        ServletContext context = null;

   try{
            configFileURL = 
HibernatePlugIn.
class.getResource(_configFilePath);
            context = servlet.getServletContext();
            configuration = (new Configuration()).configure(configFileURL);
            _factory = configuration.buildSessionFactory();
      //Set the factory into session
      context.setAttribute(SESSION_FACTORY_KEY, _factory);

   }catch(HibernateException e){
    System.out.println("Error while initializing hibernate: " + e.getMessage());
   }
   System.out.println("**************** *********************");

   }

    /**
     * Setter for property configFilePath.
     @param configFilePath New value of property configFilePath.
     */
    public void setConfigFilePath(String configFilePath) {
        if ((configFilePath == null|| (configFilePath.trim().length() == 0)) {
            throw new IllegalArgumentException("configFilePath cannot be blank or null.");
        }
        
        System.out.println("Setting ' configFilePath' to '"  + configFilePath + "'...");
        _configFilePath = configFilePath;
    }


/*(SessionFactory) servletContext.getAttribute
(HibernatePlugIn.SESSION_FACTORY_KEY);
*/
  
}


In our plugin class we have define a variable _configFilePath to hold the name of Hibernate Configuration file.

private String _configFilePath = "/hibernate.cfg.xml";

Following code define the key to store the session factory instance in the Servlet context.

public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName();

The init() is called on the startup of the Struts Application. On startup the session factory is initialized and cached in the Servlet context.

configFileURL = HibernatePlugIn.class.getResource(_configFilePath);
context = servlet.getServletContext();
configuration = (new Configuration()).configure(configFileURL);
_factory = configuration.buildSessionFactory();
//Set the factory into session
context.setAttribute(SESSION_FACTORY_KEY, _factory);

Changes to be done in struts-config.xml file

Configuring Hibernate with Struts is very simple work it requires you to have hibernate.cfg.xml in your WEB-INF/classes directory, and to add the following line to the struts-config.xml file.

<plug-in className="roseindia.net.plugin.HibernatePlugIn"></plug-in>

Testing the Plugin

Build your application and deploy on the tomcat server. Start tomcat server and observe the console output. It should display the following line:

 
 log4j:WARN Please initialize the log4j system properly.
*************************************
**** Initilizing HibernatePlugIn **********
*************************************
Aug 7, 2006 10:09:53 AM org.apache.struts.tiles.TilesPlugin initD
  

This means you have successfully configured your Struts Hibernate Plugin with struts application.

                         

» View all related tutorials
Related Tags: c apache http hibernate deployment com file j2ee ant development ui process build application script software struts io cgi download

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

11 comments so far (
post your own) View All Comments Latest 10 Comments:

Hi,

This was really a very nice article.

Cheers,

Ujjwal B Soni

Posted by ujjwal sioni on Monday, 11.17.08 @ 00:18am | #81732


is it necessary to use pulgin to integrate struts and hibernate

Posted by kk on Thursday, 09.18.08 @ 16:20pm | #80304

I am writing a struts-hibernate plugin. I wrote a plugin for hibernate and inserted the plugin tag in struts-config.xml. I am getting the error " The requested resource (/strutshibernate) is not available." If I don't insert the plugin statement the page is getting displayed. In case I consider that the struts-config.xml doesnt have strutshibernate as the action path, how was it working when the plugin element <plug-in className="roseindia.net.plugin.HibernatePlugIn"></plug-in> was not entered. Could you please solve this for me.

Posted by Prasad Regula on Monday, 09.8.08 @ 20:08pm | #78055

Code is useful, but try to add execute() template where the actual session factory will going to use.

Posted by chandrakanth on Monday, 08.25.08 @ 11:31am | #74973

Code is useful ,but it give null pointer exception...plse slove this ..when run

thanks in advance

raghavendra

Posted by raghavendra on Monday, 06.9.08 @ 15:25pm | #62710

Hi,
I found this tutorial very useful for integrating hibernate with struts.

Regards

Posted by Sanjeev Srinath on Tuesday, 06.3.08 @ 16:32pm | #61954

When I download and inplement your code I am getting the following error!!
java.lang.NullPointerException
at roseindia.web.SearchTutorialAction.execute(SearchTutorialAction.java:40)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:225)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:127)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:230)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42)
at com.grems.struts.BasicFilter.doFilter(BasicFilter.java:52)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3212)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:1983)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1890)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1344)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)

Please let me know what I have to do.

Posted by Jennie on Thursday, 06.28.07 @ 23:21pm | #20349

It was nice and useful to novice people

Posted by m.venkatraju on Saturday, 03.17.07 @ 17:58pm | #11998

Hi,

good one to beginners.

regards
raju

Posted by srinivasaraju on Wednesday, 02.7.07 @ 11:33am | #6541

nice and usefull to me.
i want more information regarding hibernate

thanks
mahesh

Posted by mahesh on Thursday, 02.1.07 @ 17:25pm | #5219

Training Courses
Tell A Friend
Your Friend Name
Website Designing Services
 
Web Designing Packages From $150!
 
Website Designing Company Web Hosting
 
Website Designing Quotation
 
Search Tutorials:

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.