Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Struts Struts 2 Example Tutorial >>> Struts2 HibernateSession Plugin >>> Struts 2 Example with Code
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
Struts2 example tutorial
Description : My First example using Apache Struts2
More...


Written By : ISHTEK
Title :
Struts2
Description : Tags such as IF Iterator Tags
More...


Written By : guddu
Title :
Struts Eclipse MVC
Description : Step by step demonstration
More...


Written By : Girish
Title :
Struts Tiles I18N Example
Description : Code with Sample Action
More...


Written By : ISHTEK
Title :
Struts2 questions
Description : open for discussion
More...


Written By : ISHTEK
Title :
Struts2 Tiles Example
Description : with Code and article
More...

Tags/Keywords : Struts, Struts2 Tutorial, Struts 2 Example, Struts2
Author : Amit
Date (Year/Month/Date): 2009-04-26 Struts2 HibernateSession Plugin Example with Code

Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this 
as it is without appropriate evaluation to their, so to say, 
specific programming context.

This page intends only to provide bit and piece of known ways  for
doing some sort of example and may not be fit for any other purpose.

This example is going to demonstrate usage of Struts2 Hibernate Session Plugin
along with Struts2 Validation and a complete end to end working example, as to
show Hibernate Session per action pattern.

My Software environment for this example:
1. Eclipse 3.2
2. JDK 1.5
3. Hibernate 3.2
4. Struts Version 2.0
5. Tomcat 5.5.x

This means a single Hibernate Session can be obtained and injected to Action
for saving example User information to database table.

While passing example user information from one action to another, usage of
SessionAware and ServletRequestAware interfaces from Struts2 are also shown.

Idea of this example is to show an example screen for user to fillin in details
and then on click of "Register" button, a preview page with user information
would be visible. On submission of the preview page, finally this set of 
example user dummy information would be saved in database table "User".

In oder to be able to use Hibernate Session Plugin for Struts2
"struts2-hibernatesession-plugin-1[1].5c.jar", in struts.xml file package
should extend "hibernatesession-default", and some of the constant values
are to be provided for the Plugin to use.

Basically this Hibernate Session Plugin, takes these Constants values from
struts.xml file, and retrieves Hibernate Session from the value for
"struts2hibernateplugin.defaults.sessionFactoryClass" using getSession
method as defined in the "struts2hibernateplugin.defaults.sessionSource"
constant. In this example sessionFactoryClass is provided in form of 
"sample.SessionFactoryProvider.java" class, and this SessionFactory Provider
class takes Hibernate SessionFactory from a singleton class "sample.SessionFactoryHolder.java", and this singleton object gets the actual
Sessionfactory from a Servlet "sample.SessionFactoryCreator.java", with 
load-on-startup as 1 from web.xml file.

<<Example Home>>
|
|-index.jsp
|-preview.jsp
|-main.jsp
|-(WEB-INF)-web.xml
|-(WEB-INF)-classes-(hibernate-config.xml)
|-(WEB-INF)-classes-struts.xml
|-(WEB-INF)-classes-User.hbm.xml
|-(WEB-INF)-classes-sample-ConsentOptions.java
|-(WEB-INF)-classes-sample-ExamplePOJOAction.java
|-(WEB-INF)-classes-sample-ExampleSaveAction.java
|-(WEB-INF)-classes-sample-MyBean.java
|-(WEB-INF)-classes-sample-SessionFactoryCreator.java
|-(WEB-INF)-classes-sample-SessionFactoryHolder.java
|-(WEB-INF)-classes-sample-SessionFactoryProvider.java
|-(WEB-INF)-classes-sample-SubscriptionOptions.java
|-(WEB-INF)-classes-sample-User.java
|-(WEB-INF)-classes-sample-(ExamplePOJOAction-validation.xml)

Advertisement :
All the parts of this example summarized as below: All these source codes are provided on "AS IS" basis, and with no guaranty or warranty of any kind. User should take appropriate caution while using these. index.jsp
<%@ taglib uri="/struts-tags" prefix="struts2"%>
<html>
<body>
<struts2:actionerror/>
<struts2:bean id="so" name="sample.SubscriptionOptions"/>
<struts2:bean id="consentOption" name="sample.ConsentOptions"/>
<struts2:form method="post" action="example" namespace="/sample">
<table>
<tr><td><struts2:textfield key="myBean.userName" label="Name "/></td></tr>
<tr><struts2:textfield key="myBean.roll" label="Roll "/></td></tr>
<tr><td><struts2:textfield key="myBean.section" label="Section "/></td></tr>
<tr><struts2:textfield key="myBean.stdClass" label="Std/Class "/></td></tr>
<struts2:checkbox key="myBean.newsLetterOption" label="Subscription for News Letters "/>
<struts2:checkboxlist label="Other Subscription Options " key="myBean.subscriptionOptions" list="so" labelSeparator=":"/>
<struts2:radio label="You opinion " key="myBean.consentOptions" list="consentOption" labelSeparator=":"/>
<tr><td colspan="2"><struts2:submit value="Register"/></td></tr>
</table>
</struts2:form>
</body>
</html>
preview.jsp
<%@ taglib uri="/struts-tags" prefix="struts2"%>
<html>
<head></head>
<body>
<h2>Preview Page</h2>
<struts2:form method="post" action="exampleSave" namespace="/sample">
<table>
<tr><td>
<b><font color="green">Name : </font>
</td><td><struts2:property value="myBean.userName"/></td></tr>
<tr><td><b><font color="green">Roll No. : </font></b></td>
<td><struts2:property value="myBean.roll"/></td></tr>
<tr><td><b><font color="green">Section : </font></b></td>
<td><struts2:property value="myBean.section"/></td></tr>
<tr><td><b><font color="green">Std/Class : </font></b></td>
<td><struts2:property value="myBean.stdClass"/></td>
</tr>
<tr><td><b><font color="green">New Letter Subscription :</font></b></td>
<td>
<struts2:if test="myBean.newsLetterOption">
Yes
</struts2:if>
<struts2:else>
No
</struts2:else>
</td></tr>
<tr><td valign="top"><b><font color="green">Other Subscription Options:</font></b></td><td>
<struts2:iterator id="a" value="myBean.subscriptionOptions">
<struts2:property value="a"/>
<br>
</struts2:iterator>
</td></tr>
<tr><td valign="top"><b><font color="green">User consent Option selected :</font></b></td><td>
<struts2:iterator id="b" value="myBean.consentOptions">
<struts2:property value="b"/>
<br>
</struts2:iterator>
</td></tr>
<tr><td colspan="2"><struts2:submit value="Submit"/></td></tr>
</table>
</struts2:form>
</body>
</html>
main.jsp
<%
out.println("Information saved successfully...");
%>
SQL used with Hibernate HBM Mapping (for HSQLDB as database)
create table User
(user_name varchar(50),
 user_roll varchar(10),
 user_section varchar(2),
 user_stdclass varchar(2), primary key (user_name))
web.xml
 <?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <display-name>Struts Hibernate Plugin</display-name>
  <servlet>
    <servlet-name>sessionfactorycreator</servlet-name>
    <servlet-class>sample.SessionFactoryCreator</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <filter>
  <filter-name>sample-filter</filter-name>
  <filter-class>  
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sample-filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
List of JAR files required for my example to work : struts.xml (placed under WEB-INF/classes folder)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="hibernate-example" namespace="/sample"
             extends="hibernatesession-default">
        <action name="example" class="sample.ExamplePOJOAction" method="preview">
            <result name="preview">/preview.jsp</result>
            <result name="main">/main.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
        <action name="exampleSave" class="sample.ExampleSaveAction" method="save">
            <result name="main">/main.jsp</result>
        </action>
    </package>
    <constant name="struts2hibernateplugin.defaults.sessionFactoryClass"  value="sample.SessionFactoryProvider"></constant>
    <constant name="struts2hibernateplugin.defaults.sessionSource"  value="session"></constant>
    <constant name="struts2hibernateplugin.defaults.closeSessionAfterInvoke"  value="true"></constant>
    <constant name="struts2hibernateplugin.defaults.staticGetSessionMethod"  value="false"></constant>
    <constant name="struts2hibernateplugin.defaults.target" value="session"></constant>
</struts>
hibernate-config.xml (placed under WEB-INF/classes folder)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">
                  org.hsqldb.jdbcDriver
        </property>
        <property name="connection.url">
                  jdbc:hsqldb:hsql://localhost
        </property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
        <!-- SQL dialect -->
        <property name="dialect">
                  org.hibernate.dialect.HSQLDialect
        </property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <mapping resource="User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="sample">
  <class name="User" table="User">
        <id name="userName" access="property" column="user_name"/>
        <property name="roll" column="user_roll"/>
        <property name="section" column="user_section"/>
        <property name="stdClass" column="user_stdclass"/>
  </class>
</hibernate-mapping>
SessionFactoryCreator.java
package sample;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class SessionFactoryCreator extends HttpServlet
{
    public void init(ServletConfig cfg)
    {
        try{
        Configuration conf = new
                        Configuration().configure("hibernate-config.xml");
        SessionFactory sessFactory = conf.buildSessionFactory();
        SessionFactoryHolder.getInstance().setSessionFactory(sessFactory);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}
SessionFactoryHolder.java
package sample;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class SessionFactoryHolder 
{
    private final static SessionFactoryHolder sessFactoryHolder 
                                   = new SessionFactoryHolder();
    private SessionFactory sessFactory;
    private SessionFactoryHolder() {
    }
    public static SessionFactoryHolder getInstance() {
        return sessFactoryHolder;
    }
    public void setSessionFactory(SessionFactory argSessFactory) {
        this.sessFactory = argSessFactory;
    }
    public Session getSession() {
        if(sessFactory != null) {
            return sessFactory.openSession();
        } else {
            return null;
        }
    }
}
SessionFactoryProvider.java
package sample;
import org.hibernate.Session;

public class SessionFactoryProvider
{
    private Session session;

    public void setSession(Session argSession) {
        System.out.println("*****************"+argSession);
        this.session = argSession;
    }
    public Session getSession() {
        return (Session)SessionFactoryHolder.getInstance().getSession();
    }
}
ExamplePOJOAction.java
package sample;
import org.hibernate.Session;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.*;

public class ExamplePOJOAction extends ActionSupport 
                               implements ServletRequestAware
{
    private Session session;
    private MyBean myBean;
    private HttpServletRequest httpRequest;

    public String preview() throws Exception {
        setValues(httpRequest.getSession(true));
        return "preview";
    }
    public void setMyBean(MyBean argMyBean) {
        myBean = argMyBean;
    }
    public MyBean getMyBean() {
        return myBean;
    }
    public void setSession(Session argSession) {

        this.session = argSession;
    }
    public Session getSession() {
        return this.session;
    }
    public void setValues(HttpSession session) {
        if(myBean != null) {
        session.putValue("myBean.userName",myBean.getUserName());
        session.putValue("myBean.roll",myBean.getRoll());
        session.putValue("myBean.section",myBean.getSection());
        session.putValue("myBean.stdClass",myBean.getStdClass());
        }
    }
    public void setServletRequest(HttpServletRequest request) {
        this.httpRequest = request;
    }
}
ExampleSaveAction.java
package sample;
import org.hibernate.Session;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;

public class ExampleSaveAction extends ActionSupport implements SessionAware
{
    private Session session;
    private Map values;
    public String save() {
        User user = new User();
        user.setUserName((String)values.get("myBean.userName"));
        user.setRoll((String)values.get("myBean.roll"));
        user.setSection((String)values.get("myBean.section"));
        user.setStdClass((String)values.get("myBean.stdClass"));
        try{
            getSession().beginTransaction();
            getSession().save(user);
            getSession().getTransaction().commit();
        } catch(Exception ex) {
            getSession().getTransaction().rollback();
            ex.printStackTrace();
        }
        return "main";
    }
    public void setSession(Map argValues) {
        this.values = argValues;
    }
    public void setSession(Session argSession) {
        this.session = argSession;
    }
    public Session getSession() {
        return this.session;
    }
}
MyBean.java
package sample;
import java.util.List;
import java.util.ArrayList;

public class MyBean
{
    private String userName;
    private String roll;
    private String section;
    private String stdClass;
    private List subscriptionOptions;
    private List consentOptions;
    private boolean newsLetterOption;

    public String getUserName() {
        return this.userName;
    }
    public void setUserName(String argUserName) {
        userName = argUserName;
    }
    public String getRoll() {
        return this.roll;
    }
    public void setRoll(String argRoll) {
        roll = argRoll;
    }
    public String getSection() {
        return this.section;
    }
    public void setSection(String argSection) {
        section = argSection;
    }
    public String getStdClass() {
        return this.stdClass;
    }
    public void setStdClass(String argStdClass) {
        stdClass = argStdClass;
    }
    public List getSubscriptionOptions() {
        return subscriptionOptions;
    }
    public void setSubscriptionOptions(List argSubscriptionOptions) {
        subscriptionOptions = argSubscriptionOptions;
    }
    public void setConsentOptions(List argConsentOptions) {
        consentOptions = argConsentOptions;
    }
    public List getConsentOptions() {
        return consentOptions;
    }
    public void setNewsLetterOption(boolean argNewsLetterOption) {
        newsLetterOption = argNewsLetterOption;
    }
    public boolean getNewsLetterOption() {
        return newsLetterOption;
    }
}
SubscriptionOptions.java
package sample;
import java.util.ArrayList;

public class SubscriptionOptions extends ArrayList
{
    public SubscriptionOptions() {
        super();
        add("Technical Support");
        add("Business Support");
        add("HR Support");
        add("Help Desk Emails");
    }

}
ConsentOptions.java
package sample;
import java.util.ArrayList;

public class ConsentOptions extends ArrayList
{
    public ConsentOptions() {
        super();
        add("Agree");
        add("Disagree");
    }
}
User.java
package sample;

public class  User
{
    private String userName;
    private String roll;
    private String section;
    private String stdClass;
    public String getUserName() {
        return this.userName;
    }
    public void setUserName(String argUserName) {
        userName = argUserName;
    }
    public String getRoll() {
        return this.roll;
    }
    public void setRoll(String argRoll) {
        roll = argRoll;
    }
    public String getSection() {
        return this.section;
    }
    public void setSection(String argSection) {
        section = argSection;
    }
    public String getStdClass() {
        return this.stdClass;
    }
    public void setStdClass(String argStdClass) {
        stdClass = argStdClass;
    }
}
ExamplePOJOAction-validation.xml
<!DOCTYPE validators PUBLIC
  		"-//OpenSymphony Group//XWork Validator 1.0.3//EN"
  		"http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">
<validators>
  <field name="myBean.userName">
    <field-validator type="requiredstring">
      <message>Please enter User name</message>      
    </field-validator>
  </field>
</validators>
Advertisement :
Author of this article/writeup has expressed his/her willingness
to help or guide users with any technical difficulties he/she faces while working with the example code environment setting up, running and resolving any such exception raised during compile or at runtime. You may ask for any technical doubt or seek technical help related to this article by using following form to reach for technical help from the Author for FREE. This article's Author shall be reading your request and responding within reasonable time (no resolution timeframe defined as such).


	

Commented By ->
sudha
hi where will u download the "struts2-hibernatesession-plugin-1[1].5c.jar"


Commented By ->
Amit
Hi Sudha,

This plugin jar can be found at

http://code.google.com/p/hibernatesession-plugin-for-struts2/downloads/list
Are you interested in solving a very interesting Technology Stack while Playing this Game          

Please write your Comment on this Matter
(This will be visible if found suitable):
Name: *
Email (will not be displayed): *
Matter: *
24,24
Enter bigger number from above :*
Home >>> Struts Struts 2 Example Tutorial >>> Struts2 HibernateSession Plugin >>> Struts 2 Example with Code
Visitor/User referred related external URL:
(Visible upon review and approved by this site Administrator)
Referred By Name *:
Resource URL *: (e.g, URL should be starting with http://www.-----.---)
 
Resource Short Description *:
23,34
Enter bigger number from above : *

Please log in to add or reply to any matter<- requires login
Log in or Register
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
CONTACT    PRIVACY POLICY    DISCLAIMER
Terms of Use and Disclaimer :

This web site provides some of the information about various technologies, example 
code, tips, tutorials etc. Like any printed materials, content of these pages may 
become out of date over a period of time. Therefore all visitor/users of this web 
site are requested/advised to refer to the originating parties/sources for the 
latest changes and happenings for detailed information. This information is not 
intended to be a substitute for the original reference provided by the originating 
parties/sources.

By accessing and using this website in any ways, including, without
limitation, browsing the website pages, using any information, using any content and/or 
downloading any materials, you agree to and are bound by the terms of use 
described in this page and Usage Terms and Conditions. 
If you do not agree to all of 
the terms and conditions contained in the terms of use described in this
page and Usage Terms and Conditions, do not use this 
website in any manner. If you are using the website on behalf of your 
employer, you represent that you are authorized to accept these Terms of Use 
on your employer's behalf.

All Trademarks are property of their respective owner. Appropriate measure is being
taken for providing accurate and up-to-date information but like any printed materials,
these blog(s)/contents may eventually be outdated one day, so if you are using any 
of these information, please refer original content/documentation from respective sources. 
And under no circumstances shall the Author of these contents and/or this web site
be liable for any loss, damage, expense incurred or suffered which is claimed to have
occurred because of usage of the contents of this web site.
If you have any questions/queries/feedback/suggestions then please write to this web
site owner at contact.