Struts 2 + Spring + Hibernate integration

bawltherapistSoftware and s/w Development

Dec 13, 2013 (3 years and 7 months ago)

76 views

Struts 2 +
S
pring

+ Hibernate integration

1.

Create project structure.

-

Create new
Dynamic Web Project: File


New


Dynamic Web Project.

-

Enter name of project, select dynamic web module version is 2.5 then click
finish
.



-

Right click on “src” folder and
create folder “main
\
java” to store java source code and
create folder “main
\
resources” to store configure files.


-

After create project structure look like that:


-

Add these folders to class path:
Right click on project, Build Path


Configure Build
Path.


-

Select
the
Source

tab. Click “Add Folder” button to add “main
\
java” and
“main
\
configures” folder to class path.



-

Remove “src” folder in class path.



-

After remove class path look like that:


2.

Create database
.

Customer’s table script.

CREATE

TABLE

customer (


CUSTOMER_ID bigint(20) unsigned
NOT

NULL

AUTO_INCREMENT,


NAME
varchar
(45)
NOT

NULL
,


ADDRESS
varchar
(255)
NOT

NULL
,


CREATED_DATE datetime
NOT

NULL
,


PRIMARY

KEY

(CUSTOMER_ID)

) ENGINE=InnoDB AUTO_INCREMENT=17
DEFAULT

CHARSET=utf8;


3.

Ad
d libraries
.

Copy
all libraries to lib folder “
WebContent
\
WEB
-
INF
\
lib
”:


4.

Create Dao layer
.

-

Create

Customer

model and mapping file:


Customer.java

package

com.mkyong.customer.model;


import

java.util.Date;


public

class

Customer

implements

java.io.Serializable {



private

Long
customerId
;


private

String
name
;


private

String
address
;


private

Date
createdDate
;



public

Customer() {


}



public

Customer(String name, String address, Date createdDate) {



this
.
name

= name;



this
.
address

= address;



this
.
createdDate

= createdDate;


}



public

Long getCustomerId() {



return

this
.
customerId
;


}



public

void

setCustomerId(Long customerId) {



this
.
customerId

= customerId;


}



public

String getName() {



return

this
.
name
;


}



public

void

setName(String name) {



this
.
name

= name;


}



public

String getAddress() {



return

this
.
address
;


}



public

void

setAddress(String address) {



this
.
address

= address;


}



public

Date getCreatedDate() {



return

this
.
createdDate
;


}



public

void

setCreatedDate(Date createdDate) {



this
.
createdDate

= createdDate;


}


}


Customer.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"
>

<!
--

Generated 20
Julai

2010 11:40:18 AM by
Hibernate

Tools 3.2.5.Beta
--
>

<
hibernate
-
mapping
>


<
class

name
=
"com.mkyong.customer.model.Customer"




table
=
"customer"

catalog
=
"mkyong"
>


<
id

name
=
"customerId"

type
=
"java.lang.Long"
>


<
column

name
=
"CUSTOMER_ID"

/>


<
generator

class
=
"identity"

/>


</
id
>


<
property

name
=
"name"

type
=
"string"
>


<
column

name
=
"NAME"

length
=
"45"

not
-
null
=
"true"

/>


</
property
>


<
property

name
=
"address"

type
=
"string"
>


<
column

name
=
"ADDRESS"

not
-
null
=
"true"

/>


</
property
>


<
property

name
=
"createdDate"

type
=
"timestamp"
>


<
column

name
=
"CREATED_DATE"

length
=
"19"

not
-
null
=
"true"

/>


</
property
>


</
class
>

</
hibernate
-
mapping
>


CustomerDAO
.java

package

com.mkyong.customer.dao;


import

java.util.List;


import

com.mkyong.customer.model.Customer;


public

interface

CustomerDAO

{



void

addCustomer(Customer customer);



List<Customer> listCustomer();


}


CustomerDAOImpl.java

package

com.mkyong.customer.dao.impl;


import

java.util.List;


import

org.springframework.orm.hibernate3.support.HibernateDaoSupport;


import

com.mkyong.customer.dao.CustomerDAO;

import

com.mkyong.customer.model.Customer;



public

class

CustomerDAOImpl

extends

HibernateDaoSupport
implements

CustomerDAO{




//add the customer


public

void

addCustomer(Customer customer){






getHibernateTemplate
().save(customer);





}




//return all the customers in list


public

List<Customer> listCustomer(){






return

getHibernateTemplate().find(
"from Customer"
)
;





}



}


5.

Create service layer
.

CustomerBo.java

package

com.mkyong.customer.bo;


import

java.util.List;


import

com.mkyong.customer.model.Customer;


public

interface

CustomerBo

{



void

addCustomer(Customer customer);



List<Customer> listCustomer();


}


CustomerBoImpl.java

package

com.mkyong.customer.bo.impl;


import

java.util.List;


import

com.mkyong.customer.bo.CustomerBo;

import

com.mkyong.customer.dao.CustomerDAO;

import

com.mkyong.customer.model.Customer;



public

class

CustomerBoImpl

implements

CustomerBo{




CustomerDAO
customerDAO
;



//DI via Spring


public

void

setCustomerDAO(
CustomerDAO customerDAO) {



this
.
customerDAO

= customerDAO;


}



//call DAO to save customer


public

void

addCustomer(Customer customer){






customerDAO
.addCustomer(customer);





}




//call DAO to return customers


public

List<Customer>

listCustomer(){






return

customerDAO
.listCustomer();





}



}


6.

Struts2
.

CustomerAction.java

package

com.mkyong.customer.action;


import

java.util.ArrayList;

import

java.util.Date;

import

java.util.List;


import

com.mkyong.customer.bo.CustomerBo;

import

com.mkyong.customer.model.Customer;

import

com.opensymphony.xwork2.ActionSupport;


public

class

CustomerAction

extends

ActionSupport{


private

String
name
;


private

String
address
;



List<Customer>
customerList

=
new

ArrayList<Customer>();



CustomerBo
customerBo
;


//DI via Spring


public

void

setCustomerBo(CustomerBo customerBo) {



this
.
customerBo

= customerBo;


}



public

List<Customer> getCustomerList() {



return

customerList
;


}



public

void

setCustomerList(List<Customer>

customerList) {



this
.
customerList

= customerList;


}



//save customer


public

String addCustomer()
throws

Exception{



Customer customer =
new

Customer();



// Set value for customer.



customer.setName(
name
);



customer.setAddress(
address
);



customer
.setCreatedDate(
new

Date());



customerBo
.addCustomer(customer);




//reload the customer list



customerList

=
null
;



customerList

=
customerBo
.listCustomer();




return

"success"
;



}



//list all customers


public

String listCustomer()
throws

Exception{




customerList

=
customerBo
.listCustomer();




return

"success"
;



}



/**



*
@return

the name



*/


public

String getName() {



return

name
;


}



/**



*
@param

name the name to set



*/


public

void

setName(String name) {



this
.
name

= name;


}



/**



*
@return

the address



*/


public

String getAddress() {



return

address
;


}



/**



*
@param

address the address to set



*/


public

void

setAddress(String address) {



this
.
address

= address;


}

}


7.

Create spring’s bean configuration

file.

Almost all the
spring’s
configuration is done here
:



CustomerBean.xml
:
Declare the
spring’s

beans:

Action, BO and DAO.

<?
xml

version
=
"1.0"

encoding
=
"UTF
-
8"
?>

<
beans

xmlns
=
"http://www.springframework.org/schema/beans"


xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema
-
instance"


xsi:schemaLocation
=
"http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring
-
beans
-
2.5.xsd"
>




<
bean

id
=
"customerAction"

class
=
"com.mkyong.customer.action.CustomerAction"
>



<
property

name
=
"customerBo"

ref
=
"customerBo"

/>


</
bean
>



<
bean

id
=
"customerBo"

parent
=
"txProxyTemplate"
>



<
property

name
=
"target"
>




<
bean

class
=
"com.mkyong.customer.bo.impl.CustomerBoImpl"
>




<
property

name
=
"customerDAO"

ref
=
"customerDAO"

/>



</
bean
>


</
property
>


</
bean
>




<
bean

id
=
"customerDAO"

class
=
"com.mkyong.customer.dao.impl.CustomerDAOImpl"

>



<
property

name
=
"sessionFactory"

ref
=
"sessionFactory"

/>


</
bean
>


</
beans
>


database.properties:

Declare

the database details.

jdbc.driverClassName=
com.mysql.jdbc.Driver

jdbc.url=
jdbc
:
mysql://
localhost
:3306/fresher

jdbc.username=
root

jdbc.password=
123456


DataSource.xml
:
Create a datasource bean.

<
beans

xmlns
=
"http://www.springframework.org/schema/beans"

xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema
-
instance"

xsi:schemaLocation
=
"http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring
-
beans
-
2.5.xsd"
>



<
bean


class
=
"org.springframework.beans.factory.config.PropertyPlac
eholderConf
igurer"
>


<
property

name
=
"location"
>


<
value
>
classpath:config/database/properties/database.properties
</
value
>


</
property
>

</
bean
>



<
bean

id
=
"dataSource"


class
=
"org.springframework.jdbc.datasource.DriverManagerDataSource"
>


<
property

name
=
"driverClassName"

value
=
"${jdbc.driverClassName}"

/>


<
property

name
=
"url"

value
=
"${jdbc.url}"

/>


<
property

name
=
"username"

value
=
"${jdbc.username}"

/>


<
property

name
=
"password"

value
=
"${jdbc.password}"

/>


</
bean
>


</
beans
>


HibernateSessionFactory.xml

:
Create a

sessionFactory

bean to integrate Spring and
Hibernate.

<?
xml

version
=
"1.0"

encoding
=
"UTF
-
8"
?>

<
beans

xmlns
=
"http://www.springframework.org/schema/beans"

xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema
-
instance"

xsi:schemaLocation
=
"http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring
-
beans
-
2.5.xsd"
>



<!
--

Hibernate

session factory
--
>

<
bean

id
=
"sessionFactory"



class
=
"org.springframework.orm.hibernate3.LocalSessionFac
toryBean"
>




<
property

name
=
"dataSource"
>


<
ref

bean
=
"dataSource"
/>


</
property
>




<
property

name
=
"hibernateProperties"
>


<
props
>


<
prop

key
=
"hibernate.dialect"
>
org.hibernate.dialect.MySQLDialect
</
prop
>


<
prop

key
=
"hibernate.show_sql"
>
true
</
prop
>


</
props
>


</
property
>




<
property

name
=
"mappingResources"
>



<
list
>


<
value
>
com
/
mkyong
/customer/
hibernate
/Customer.hbm.xml
</
value
>



</
list
>


</
property
>




</
bean
>

</
beans
>


TransactionManager.xml
: Create transaction manager beans

for manager transaction
.

<
beans

xmlns
=
"http://www.springframework.org/schema/beans"

xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema
-
instance"

xsi:schemaLocation
=
"http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring
-
beans
-
2.5.xsd"
>


<
bean

id
=
"txProxyTemplate"

abstract
=
"true"

class
=
"org.springframework.transaction.interceptor.TransactionProxyFact
oryBean"
>



<
property

name
=
"t
ransactionManager"

ref
=
"transactionManager"

/>



<
property

name
=
"transactionAttributes"
>




<
props
>





<
prop

key
=
"save*"
>
PROPAGATION_REQUIRED
</
prop
>





<
prop

key
=
"add*"
>
PROPAGATION_REQUIRED
</
prop
>





<
prop

key
=
"delete*"
>
PROPAGATION_REQUIRED
</
prop
>





<
prop

key
=
"remove*"
>
PROPAGATION_REQUIRED
</
prop
>





<
prop

key
=
"insert*"
>
PROPAGATION_REQUIRED
</
prop
>





<
prop

key
=
"update*"
>
PROPAGATION_REQUIRED
</
prop
>





<
prop

key
=
"*"
>
PROPAGATION_REQUIRED,readOnly
</
prop
>




</
props
>



</
property
>


</
bean
>



<
bean

id
=
"transactionManager"

class
=
"org.springframework.orm.hibernate3.HibernateTransactionManager"
>


<
property

name
=
"sessionFactory"

ref
=
"sessionFactory"
/>


</
bean
>

</
beans
>


SpringBeans.xml
:

Create a core Spring’s bean configuration file, act as the
central bean
management.

<
beans

xmlns
=
"http://www.springframework.org/schema/beans"

xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema
-
instance"

xsi:schemaLocation
=
"http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring
-
bea
ns
-
2.5.xsd"
>



<!
--

Database Configuration
--
>


<
import

resource
=
"config/spring/DataSource.xml"
/>


<
import

resource
=
"config/spring/HibernateSessionFactory.xml"
/>


<
import

resource
=
"config/spring/TransactionManager.xml"
/>



<!
--

Beans Declaration
--
>


<
import

resource
=
"com/mkyong/customer/spring/CustomerBean.xml"
/>


</
beans
>



8.

Create JSP page.

customer.jsp

(Webcontent
\
pages
\

customer.jsp)

<%@

taglib

prefix
=
"s"

uri
=
"/struts
-
tags"

%>

<
html
>

<
head
>

</
head
>



<
body
>

<
h1
>
Struts 2 + Spring +
Hibernate

integration example
</
h1
>


<
h2
>
Add Customer
</
h2
>

<
s:form

action
=
"addCustomerAction"

>


<
s:textfield

name
=
"name"

label
=
"Name"

value
=
""

/>


<
s:textarea

name
=
"address"

label
=
"Address"

value
=
""

cols
=
"50"

rows
=
"5"

/>


<
s:submit

/>

</
s:form
>


<
h2
>
All
Customers
</
h2
>


<
s:if

test
=
"customerList.size() > 0"
>

<
table

border
=
"1px"

cellpadding
=
"8px"
>


<
tr
>



<
th
>
Customer Id
</
th
>



<
th
>
Name
</
th
>



<
th
>
Address
</
th
>



<
th
>
Created Date
</
th
>


</
tr
>


<
s:iterator

value
=
"customerList"

status
=
"userStatus"
>



<
tr
>




<
td
><
s:property

value
=
"customerId"

/></
td
>




<
td
><
s:property

value
=
"name"

/></
td
>




<
td
><
s:property

value
=
"address"

/></
td
>




<
td
><
s:date

name
=
"createdDate"

format
=
"dd/MM/yyyy"

/></
td
>



</
tr
>


</
s:iterator
>

</
table
>

</
s:if
>

<
br
/>

<
br
/>


</
body
>

</
html
>


Index.
jsp

(
Webcontent
):

<!
DOCTYPE

html

PUBLIC

"
-
//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd"
>

<
html
>

<
head
>

<
meta

http
-
equiv
=
"Refresh"

content
=
"0;URL=
<%=

request.getContextPath()
%>
/listCustomerAction.action"
>

<
title
>
Index
</
title
>

</
head
>

<
body
>

Loading...

</
body
>

</
html
>


9.

Create struts.xml file.

Struts.xml (
src
\
main
\
resources
\
struts.xml
)

<?
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
>



<
constant

name
=
"struts.devMode"

value
=
"true"

/>





<
package

name
=
"default"

namespace
=
"/"

extends
=
"struts
-
default"
>






<
action

name
=
"addCustomerAction"





class
=
"customerAction"

method
=
"addCustomer"

>




<
result

name
=
"success"
>
pages/customer.jsp
</
result
>



</
action
>





<
action

name
=
"listCustomerAction"




class
=
"customerAction"

method
=
"listCustomer"

>




<
result

name
=
"success"
>
pages/customer.jsp
</
result
>



</
action
>





</
package
>



</
struts
>


10.

Define struts and spring in web.xml.

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
>
Struts2_Spring_Hibernate
</
display
-
name
>




<!
--

Struts 2
--
>


<
filter
>


<
filter
-
name
>
struts2
</
filter
-
name
>


<
filter
-
class
>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFi
lter
</
filter
-
class
>


</
filter
>




<
filter
-
mapping
>


<
filter
-
name
>
struts2
</
filter
-
name
>


<
url
-
pattern
>
/*
</
url
-
pattern
>


</
filter
-
mapping
>





<!
--

Spring
--
>


<
context
-
param
>


<
param
-
name
>
contextConfigLocation
</
param
-
name
>


<
param
-
value
>
/WEB
-
INF/classes/SpringBeans.xml
</
param
-
value
>


</
context
-
param
>




<
listener
>


<
listener
-
class
>


org.springframework.web.context.ContextLoaderListener


</
listener
-
class
>


</
listener
>




<
welcome
-
file
-
list
>


<
welcome
-
file
>
index.
jsp
</
welcome
-
file
>


</
welcome
-
file
-
list
>

</
web
-
app
>


Complete project

structure
:





11.

Run application

http://localhost:8081/Struts2_Spring_Hibernate