Services | Updates | Contact
Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
Search All Tutorials
Top Search: Loan Struts Open Source
Open Source XML Editor
The Xerlin Project is a Java? based XML modeling application written to make creating and editing XML files easier. It r
 
Graphics2D
The javax.swing.Graphics2D class of Java 2 supports many more graphics operations than the Graphics class.
 
More Tutorials...

Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML

 
 
Struts
Comments
 
 

 

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.

                         

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

Current Comments

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

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

hi 2 all.
hello world! It is nice site. Keep working!
best regards
i found you here http://google.com ^^

Posted by marionxlx on Friday, 01.26.07 @ 17:59pm | #4429

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

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.

  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

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

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

Copyright © 2007. All rights reserved.