Struts is a set of Java classes and JSP tag libraries that uses a model-view-controller (MVC) design pattern to provide a framework for developing Web applications. It is an open source subproject of the Apache Software Foundation’s Jakarta project.
Hibernate is an open source Object/ Relational Mapping solution for Java environments. It reduces the development cost by reducing paradigm mismatch between how data is represented in objects versus relational databases. Hibernate takes care of the mapping from Java classes to database tables and provides data query and retrieval facilities.
MVC Framework – What is MVC?
Model
The action servlet selects and invokes one or more actions to perform the requested business logic. The actions manipulate the state of the application’s interaction with the user, typically by creating or modifying Java beans that are stored as request or session attributes (depending on how long they need to be available). Such Java beans represent the model component of an MVC architecture. Instead of producing the next page of the user interface directly, actions generally use the RequestDispatcher.forward() facility of the servlet API to pass control to an appropriate JSP file to produce the next page of the user interface.
Structure of Model-View-Controller Architecture

View
The user interface generally is created with JSP files that do not themselves contain any business logic. These pages represent the view component of MVC architecture.
Controller
Forms and hyperlinks in the user interface that require business logic to be executed are submitted to a request URI that is mapped to an action servlet. One instance of this servlet class exists and receives and processes all requests that change the state of a user’s interaction with the application. This component represents the controller component of MVC architecture.
There are several setup tasks that are to be performed before deploying the application. These include components in the configuration file (struts-config.xml) and in the Web Application Deployment Descriptor (web.xml). The web.xml file is where servlets and other stuff are defined to the servlet container.
Hibernate Architecture
Basic interfaces used while working with Hibernate are:
• SessionFactory
• Session
• Transaction
Hibernate Architecture

SessionFactory
SessionFactory is immutable. The behaviour of a SessionFactory is controlled by properties supplied at configuration time. These properties are defined on Environment. It Creates Sessions. Usually an application has a single SessionFactory. Threads servicing client requests obtain Sessions from the factory.
Session
The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of below three states:
• transient: never persistent, not associated with any Session
• persistent: associated with a unique Session
• detached: previously persistent, not associated with any Session
Transaction
A transaction is associated with a Session and is usually instantiated by a call to Session.beginTransaction(). A single session might span multiple transactions since the notion of a session (a conversation between the application and the datastore) is of coarser granularity than the notion of a transaction. However, it is intended that there be at most one uncommitted Transaction associated with a particular Session at any time.
Software Requirements
• JBoss Developer Studio
• Jdk 1.6
• JBoss 5.1 runtime server
• Struts 1.2
• Hibernate 3.0
• Oracle
Application SETUP
We will be creating and making use of \WebContent\WEB-INF and \src directories
web.xml
Web.xml contains tags like ,, ,, and
The file contains three sections:
• the definition of the Struts servlet named “ActionServlet”
• the URL mapping for the calls to this servlet
• the definitions of the Struts tag libraries
Tags Description
web-app Is the root element in web.xml it has sub elements like ,, and
servlet • contains sub element like , ,,
• Each web.xml file contains any number tags sub element like and
servlet-mapping Specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets
servlet-name the servlet given in servlet-name should be called
load-on-startup is used to tell container which servlet should be loaded at first when server is started
url-pattern The url path which is provided in html form action.
Syntax of web.xml:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class> org.apache.struts.action.ActionServlet </servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Struts-config.xml
Important attributes and elements of ActionMapping entry in struts-config.xml
Attribute /Element name Description
Path - The URL path (either path mapping or suffix mapping) for which this Action Mapping is used. The path should be unique.
Type - The fully qualified class name of the Action
Name - The logical name of the Form bean. The actual ActionForm associated with this Action Mapping is found by looking in the Form-bean definition section for a form-bean with the matching name. This informs the Struts application which action mappings should use which ActionForms.
Scope – Scope of the Form bean – Can be session or request
Validate - Can be true or false. When true, the Form bean is validated on submission. If false, the validation is skipped.
Input - The physical page (or another ActionMapping) to which control should be forwarded when validation errors exist in the form bean.
Forward - The physical page (or another ActionMapping) to which the control should be forwarded when the ActionForward with this name is selected in the execute method of the Action class.
Syntax of struts-config.xml:
<struts-config>
<form-beans>
<form-bean name="nameForm" type="example.NameForm"/>
</form-beans>
<action path="/Name" type="example.NameAction" name="nameForm" input="/index.jsp"> <forward name="success" path="/displayname.jsp"/>
<forward name="failure" path="/index.jsp"/>
</action>
<message-resources parameter="example.ApplicationResources"/>
</struts-config>
hibernate.cfg.xml
Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.
Hibernate configuration file has several properties such as below
Property name Purpose
hibernate.connection.driver_class JDBC driver class
hibernate.connection.url JDBC URL
hibernate.connection.username database user
hibernate.connection.password database user password
hibernate.connection.pool_size maximum number of pooled connections
hibernate.dialect The classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database. In most cases Hibernate will actually be able to choose the correct org.hibernate.dialect.Dialect implementation based on the JDBC metadata returned by the JDBC driver. e.g org.hibernate.dialect.Oracle9Dialect
hibernate.show_sql To write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug. e.g. true | false
Syntax of XML configuration file:
<hibernate-configuration>
<!-- a SessionFactory instance listed as /jndi/name -->
<session-factory
name="java:hibernate/SessionFactory">
<!-- properties -->
<property name="connection.datasource"> java:/comp/env/jdbc/MyDB</property>
<property name = "hibernate.connection.driver_class"> oracle.jdbc.driver.OracleDriver</property>
<!-- Mapping files -->
<mapping resource="empdetails.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The XML configuration file is by default expected to be in the root of CLASSPATH.The advantage of this approach is the externalization of the mapping file names to configuration. The hibernate.cfg.xml is also more convenient to tune the Hibernate cache. Either hibernate.properties or hibernate.cfg.xml can be used. Both are equivalent, except for the above mentioned benefits of using the XML syntax.
*.hbm.xml
Attribute/Element Name Purpose
id- Mapping attribute that declares the name of the JavaBean property and tells Hibernate to use.
getId() and setId() – methods to access the property. The column attribute tells Hibernate which column of the EVENTS table holds the primary key value.
property - The name attribute of the property element tells Hibernate which getter and setter methods to use
Eg.getEmpName(), setEmpName()
Syntax of mapping resource
<hibernate-mapping>
<class name="package with className " table="tableName ">
<id name="Class’s property name " type="long" column="table’s id " >
</id>
<property name="Class’s property name ">
<column name="Table’s column name " />
</property>
……….
</class>
</hibernate-mapping>
Method summary of Session Factory
Method Description
openSession() open a new Session
beginTransaction() Begin a unit of work and return the associated Transaction object.
close() End the session by releasing the JDBC connection and cleaning up.
createCriteria(Class persistentClass) Create a new Criteria instance, for the given entity class, or a superclass of an entity class.
getSession(EntityMode entityMode) Starts a new Session with the given entity mode in effect.
getSessionFactory() Get the session factory which created this session.
getTransaction() Get the Transaction instance associated with this session.
save(Object object) Persists the given transient instance, first assigning a generated identifier.
createQuery(String queryString) Create a new instance of Query for the given HQL query string.
createSQLQuery(String queryString) Create a new instance of SQLQuery for the given SQL query string.
delete(Object object) Remove a persistent instance from the datastore.
enableFilter(String filterName) Enable the named filter for this current session.
get(Class clazz, Serializable id) Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.
getNamedQuery(String queryName) Obtain an instance of Query for a named query string defined in the mapping file.
Method summary of Transaction
Method Description
begin() Begin a new transaction.
commit() Flush the associated Session and end the unit of work
rollback() Force the underlying transaction to roll back.
Method summary of Configuration
Method Description
configure() Use the mappings and properties specified in an application resource named hibernate.cfg.xml.
buildSessionFactory() Instantiate a new SessionFactory, using the properties and mappings in this configuration.
With the XML configuration Starting Hibernate is then as simple as any of the below
• SessionFactory sf = new Configuration().configure().buildSessionFactory();
• SessionFactory sf = new Configuration().configure(“hibernate.cfg.xml”).buildSessionFactory();
• SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();
To run the application, open Web browser with the following URL: http://localhost:port/example/
Sample Application
Let’s try to understand Struts with Hibernate and Oracle using a sample application!!!
This application will help you to insert a record in the database. To create the web project named EmployeeDetails using struts and hibernate follow the below steps
1. Create a web dynamic project in JBOSS named EmployeeDetails
2. Create a struts-config.xml file and web.xml file into WEB-INF folder.
3. Create hibernate.cfg.xml into Source folder
4. Create empdetails.hbm.xml into Source folder
5. Create the below packages into the source folder
• com.example.Action
• com.example.ActionForm
• com.example.model
• com.example.util
6. Create a file named EmployeeAction.java in package com.example.Action
7. Create a file named EmployeeForm.java in package com.example.ActionForm
8. Create a file named EmployeeManager.java in package com.example.util
9. Create a file named EmpVO.java in package com.example.model
10. Create the following JSPs index.jsp and welcome.jsp into WebContent folder.
11. Create a table named EMPDETAILS in Oracle
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>EmployeeDetails</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Struts-config.xml :
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
<form-beans>
<form-bean name="EmployeeForm"
type="com.example.actionForm.EmployeeForm" />
</form-beans>
<action-mappings>
<action path="/enterdata" name="EmployeeForm" validate="true" input="/index.jsp"
type="com.example.action.EmployeeAction">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/index.jsp" />
</action>
</action-mappings>
</struts-config>
hibernate.cfg.xml :
<?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>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@ ipaddress:port:DatabaseName</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password"> password</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
<!-- Mapping files -->
<mapping resource="empdetails.hbm.xml"/>
</session-factory>
</hibernate-configuration>
empdetails.hbm.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.example.model.EmpVO" table="EmpDetails">
<id column="EMP_ID" name="empID" type="java.lang.Integer" >
<generator class="increment" />
</id>
<property name="empName">
<column name="EMP_NAME" />
</property>
<property name="empPosition">
<column name="EMP_POSITION"/>
</property>
<property name="empLocation">
<column name="EMP_LOCATION"/>
</property>
</class>
</hibernate-mapping>
EmployeeAction.java
package com.example.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.example.actionForm.EmployeeForm;
import com.example.model.EmpVO;
import com.example.util.EmployeeManager;
public class EmployeeAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws HibernateException {
String Success = "success";
String Failure = "failure";
Session session = null;
// Create a database connection
SessionFactory sessionFactory = EmployeeManager.getSessionFactory();
// Open a session for the given database connection
session = sessionFactory.openSession();
List retList=null;
try {
EmployeeForm empForm = (EmployeeForm)form;
//Begin a unit of work
session.beginTransaction();
System.out.println("Inserting Record");
EmpVO newForm = new EmpVO();
newForm.setEmpName(empForm.getEmpName());
newForm.setEmpPosition(empForm.getEmpPosition());
newForm.setEmpLocation(empForm.getEmpLocation());
session.save(newForm);
session.getTransaction().commit();
retList = session.createQuery("from EmpVO").list();
request.setAttribute("empdetails", retList);
session.close();
} catch(HibernateException e){
e.printStackTrace();
return mapping.findForward(Failure);
}
return mapping.findForward(Success);
}
}
EmployeeForm.java
package com.example.actionForm;
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class EmployeeForm extends ActionForm {
private String empName;
private String empPosition;
private String empLocation;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpPosition() {
return empPosition;
}
public void setEmpPosition(String empPosition) {
this.empPosition = empPosition;
}
public String getEmpLocation() {
return empLocation;
}
public void setEmpLocation(String empLocation) {
this.empLocation = empLocation;
}
}
EmpVO.java
package com.example.model;
public class EmpVO {
private Integer empID;
private String empName;
private String empPosition;
private String empLocation;
public Integer getEmpID() {
return empID;
}
public void setEmpID(Integer empID) {
this.empID = empID;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpPosition() {
return empPosition;
}
public void setEmpPosition(String empPosition) {
this.empPosition = empPosition;
}
public String getEmpLocation() {
return empLocation;
}
public void setEmpLocation(String empLocation) {
this.empLocation = empLocation;
}
}
EmployeeManager.java
package com.example.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class EmployeeManager {
private static final SessionFactory sessionFactory;
static {
//create sessionFactory only once
//creating the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Index.jsp
<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<%@taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<html>
<head>
<title>Enter Details into DB</title>
</head>
<body>
<h1 align="center">Login</h1>
<html:form action="enterdata">
<table border="1" align="center" >
<tr>
<td><label>EmployeeName:</label></td>
<td><html:text property="empName" /></td>
</tr>
<tr>
<td><label>Position:</label></td>
<td><html:text property="empPosition" /></td>
</tr>
<tr>
<td><label>Location:</label></td>
<td><html:text property="empLocation" /></td>
</tr>
<tr>
<td align="center"><html:submit/></td>
</tr>
</table>
</html:form>
</body>
</html>
Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/lib/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/lib/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<table border="2" align="center" >
<tr>
<td>EmpID</td>
<td>EmployeeName</td>
<td>EmployeeLocation</td>
<td>EmployeePosition</td>
</tr>
<logic:present name = "empdetails">
<logic:iterate id="details" name="empdetails">
<tr>
<td><c:out value="${details.empID}" /></td>
<td><c:out value="${details.empName}" /></td>
<td><c:out value="${details.empLocation}" /></td>
<td><c:out value="${details.empPosition}" /></td>
</tr>
</logic:iterate>
</logic:present>
</table>
</body>
</html>
Empdetails in Oracle 10g
CREATE TABLE empdetails
(
EMP_NAME VARCHAR2(10),
EMP_ID INT PRIMARY KEY,
EMP_POSITION VARCHAR2(10),
EMP_LOCATION VARCHAR2(10)
)
To run the application, open Web browser with the following URL: http://localhost:8080/employeedetails/
Screenshot of Application
References
http://www.allapplabs.com/hibernate/introduction_to_hibernate.htm
http://publib.boulder.ibm.com/infocenter/wsadhelp/v5r1m2/index.jsp?topic=%2Fcom.ibm.etools.struts.doc%2Ftopics%2Fcstrdoc001.html
http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/Transaction.html
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html
http://www.tutorialsfree.net/struts-tutorial/what-is-web-xml-in-struts