Anda di halaman 1dari 9

Integrating Struts 2.

0 applications with Hibernate


February 19, 2011 Hibernate, Struts 2.0
Struts 2.0 is one of the popularly used Presentation tier framework for Java web Applications.It is based on the WebWork2 technology.Struts 2.0 framework implements MVC 2 architecture by centralizing the control using a Front Controller strategy. The extensible and flexible nature of Struts 2.0 makes it the favourite choice of Java web developers. The major features of Struts 2.0 are user interface tags, Interceptor, result and validation.

A strong persistence framework is critical to the success and scalability of any application that we develop. Today we have a lot of data access frameworks like Hibernate, JDBC, JPAs, etc available in the market. Sturts can be integrated easily with any of these popularly used data access frameworks. This article demonstrates the integration of Struts 2.0 applications with the Hibernate. The concept is explained with the help of a sample application. There are pluggins also available for integrating Struts 2.0 with Hibernate. The sample application used in this articile does not use any pluggins. The author asuumes readers of this article have basic knowledge of Struts 2.0 and Hibernate.If you are beginner in learning Struts and hibernate, please read Introduction to Struts 2.0 and Introduction to Hibernate. The sample is created in NetBens IDE. Sample project struture is displayed in the next section.

Project Structure
This application which is discussed here stores the registration details of an employee to an Oracle DB table using struts 2 and hibernate.Includ the hibernate jar files and struts 2.0 jar files to the project class path. Since we are using Oraccle we need to load the classes12.jar/odbc5.jar also to the class path.

Create the domain model Employee.java as below.This class will be used as the hibernate model object.Hence we need to have the hibernate mapping files created for this as listed in the next section. The same is used to push the form data to the valuestack.ValueStack, as you know already , is ,one of the powerful features of Struts 2.ValueStack can be defined as a storage structure where the data associated with the current request is stored. The properties of this bean is directly accessible from the JSP pages using OGNL expresion language.
Listing 1. Employee.java

1 public class Employee { 2 private int empno; 3 private String name; 4 private String jobtitle; private String unit;//business unit - Retail,Testing, etc 5 private String technology;//current working technology 6 // getter & setter methods 7} 8

Struts 2.0 Action Class Registration.java


As you are already aware of , Struts 2 do not have the ActionForm concept. But those of you ,who would like to use such a feature in Struts 2, they can create a POJO that holds the form data in its properties and then create an Action class that implements the ModelDriven interface. This is what we have done in the sample described here.

Please note that when you implement ModelDriven interface, you need to get the model object using the getModel() method. The Preparable interface is implemented here so that the action class can prepare itself. If you dont have anything to prepare, theres no reason to implement Preparable. Here we are initializing the instance of the Employee object with the prepare() method of the Preparable interface.
Listing 2 : Model Driven Action class Registration.java

1 2 package com.myaction; 3 4 import com.opensymphony.xwork2.ActionSupport; 5 import com.opensymphony.xwork2.ModelDriven; 6 import com.opensymphony.xwork2.Preparable; org.hibernate.HibernateException; 7 import import org.hibernate.Session; 8 import org.hibernate.SessionFactory; 9 import org.hibernate.Transaction; 10import org.hibernate.cfg.Configuration; 11public class Registration extends ActionSupport implements ModelDriven, Preparable { 12 13 Employee employee; 14 SessionFactory sessionFactory = null; 15 Session session = null; 16 public String execute() { 17 try { 18 sessionFactory = new 19Configuration().configure().buildSessionFactory(); 20 session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); 21 session.saveOrUpdate(employee); 22 transaction .commit(); 23 System.out.println("Record Inserted Successfully"); 24 } catch (HibernateException hibernateException) { 25 System.out.println(hibernateException.getMessage()); session.close(); 26 return "ERROR"; 27 } 28 return "SUCCESS"; 29 } 30 @Override 31 public Employee getModel() { 32 return employee; 33 } 34 @Override 35 public void prepare() throws Exception { employee = new Employee(); 36 } 37 } 38 39

40 41 In this action class we are obtaining the SessionFactory instance from the hibernate configuration. Once the SessionFactory instance is obtained, you can create the Session object and invoke the necessary methods for insertion / updation of the records in the table.

JSP Pages
We use three JSP pages in this application. The first one is the index.jsp page that accepts the registration details of the employee. Upon submiting this form, the action class execute method is invoked and data is strored in the database. Success.jsp(Listed next) will be shown to the user upon successful insertion of the data. If an error occurs during insertion , Error.jsp is displayed.
Listing 3 :index.jsp

1 <%@page contentType="text/html" pageEncoding="UTF-8"%> HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 2 <!DOCTYPE "http://www.w3.org/TR/html4/loose.dtd"> 3 <%@taglib uri="/struts-tags" prefix="s"%> 4 <html> 5 <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 6 <title>JSP Page</title> 7 </head> 8 <body> 9 <center> 1 <!-- <img src="PDT_TVM_SMall.JPG"/> --> <h1>Registration Form</h1> 0 <s:form action="Registration"> 1 <table bgcolor="pink"> 1 <tr> 1 <td> <s:textfield name="empno" label=" Employee Id " 2 value="" /> 1 </td> 3 <td> 1 <s:textfield name="name" label=" Name" /> 4 </td> <td> 1 <s:textfield name="jobtitle" label=" Job Title " 5 /> 1 </td> 6 <td> <s:combobox label=" Business Unit " name="unit" 1 headerValue="--- Please Select ---" 7 headerKey="1" 1 list="{'Retail','HR','Quality','R&D' 8 ,'Testing','Facilities'}" /> 1 </td>

<td> 9 <s:combobox label=" Current Technology Area" 2 name="technology" 0 headerValue="--- Please Select ---" 2 headerKey="1" list="{'Java','J2EE','.NET','Main 1 2 Frame','Others'}"/> </td> 2 <td colspan="0"><s:submit label="Register"/></td> 2 </tr> 3 </table> </s:form> 2 </center> 4 </body> 2 </html> 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4

2 4 3 4 4
Listing 4 : Success.jsp

1 <%@page contentType="text/html" pageEncoding="UTF-8" 2 import="com.myaction.Employee"%> 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <%@taglib prefix="s" uri="/struts-tags"%> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>JSP Page</title> </head> 9 <body><center> 10 <br> <br> <br> <br> 11 <h1 style="color:chocolate"> <s:property value="name"/> 12registered successfully !!</h1> </center> 13 </body> 14 15</html>
Listing 5 : Error.jsp

1 2 <%@page contentType="text/html" pageEncoding="UTF-8" errorPage="Error.jsp"%> 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Error Page</title> 8 </head> 9 <body> 10 <h1>Some Error Occurred !! </h1> 11 </body> 12</html> 13

Oracle Database table structure

Listing 6 : web.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 4 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 5 <filter> <filter-name>struts2</filter-name> 6 <filter7 class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 8 </filter> 9 <filter-mapping> <filter-name>struts2</filter-name> 10 <url-pattern>/*</url-pattern> 11 </filter-mapping> 12 <session-config> 13 <session-timeout> 14 30 </session-timeout> 15 </session-config> 16 <welcome-file-list> 17 <welcome-file>index.jsp</welcome-file> 18 </welcome-file-list> 19</web-app>

Hibernate and Struts 2 configuration files


Listing 7 : Struts.xml

1 <!DOCTYPE struts PUBLIC 2 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 3 "http://struts.apache.org/dtds/struts-2.0.dtd">

4 5 <struts> <!-- Configuration for the default package. --> 6 <package name="default" extends="struts-default"> 7 <action name="Registration" class="com.myaction.Registration"> 8 <result name="SUCCESS">/Success.jsp</result> <result name="ERROR">/Error.jsp</result> 9 </action> 10 </package> 11</struts> 12 13
Listing 8 : hibernate.cfg.xml Hibernate configuration file

1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5

<?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.dialect">org.hibernate.dialect.Oracle8iDialect</property> <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@10.154.117.76:1521:oracle< /property> <property name="hibernate.connection.username">user</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <mapping resource="Employee.hbm.xml"/> </session-factory> </hibernate-configuration>

Listing 9 : Employee.hbm.xml hibernate mapping file

1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <hibernate-mapping> 5 <class name="com.myaction.Employee" table="StrutsHibEmployee"> <id column="EMPNO" name="empno" type="int"> 6 <generator class="assigned"/> 7 </id> 8 <property column="EMPNAME" name="name" type="string"/> 9 <property column="ROLE" name="jobtitle" type="string"/> <property column="UNIT" name="unit" type="string"/> 10

<property column="TECHNOLOGY" name="technology" type="string"/> 11 </class> 12 </hibernate-mapping> 13 14

Run the application. Sample screen shots are shown below.

Output can be verified in the database as below.

Summary
Integrating Struts 2.0 with Hibernate is very simple. From the sample explained in the article, you can see that there is no need of using any separate pluggins for this. What is required is to get the SessionFactory object in the Action class and use it the way you use it in normal Java Applications.

Anda mungkin juga menyukai