Thursday, January 13, 2011

Struts, Spring integration with hibernate

Integrate Struts Spring Hibernate Web Application

This example guides you to Integrate Struts Spring Hibernate in a web application. 
Struts : View (User Interface) 
Spring : Service Layer 
Hibernate : DAO layer 

Here are the steps for Integration Struts Spring Hibernate Web Application.

Struts Part 

Step 1. Add ActionServlet in web.xml
ActionServlet 

ActionServlet is the controller in Struts.
ActionServlet loads the struts-config.xml.
On load-on-startup the servlet container Instantiate the ActionServlet . 
First Task by ActionServlet : The ActionServlet takes the Struts Config file name as an init-param. 
At startup, in the init() method, the ActionServlet reads the Struts Config file and load into memory. 
Second Task by ActionServlet : If the user types http://localhost:8081/strutsspringhibernate/userForm.do 
in the browser URL bar, the URL will be intercepted and processed by the ActionServlet since the URL has a pattern *.do, with a suffix of "do". Because servlet-mapping is 


<servlet-mapping> 
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

Third Task by ActionServlet : Then ActionServlet delegates the request handling to another class called RequestProcessor by invoking its process() method. 

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


Step 2. add ActionMapping in struts-config.xml
http://localhost:8081/strutsspringhibernate/userForm.do call to /jsp/userForm.jsp jsp.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
<form-beans>
<form-bean name="UserForm" type="com.UserForm"> </form-bean>
</form-beans>

<action-mappings>
<action path="/userForm"
type="org.apache.struts.actions.ForwardAction"
parameter="/jsp/userForm.jsp"/>

<action path="/saveUser"
type="com.UserSaveAction"
name="UserForm"
scope="request"
validate="false"
input="/pages/Input.jsp">
<forward name="success" path="/jsp/success.jsp"/>
</action> 
</action-mappings>
</struts-config>

Enter username and deptname and click the Save button. 
Save button calls /saveUser.do , saveUser.do calls com.UserSaveAction based on above configuration in struts-config.xml. 

Step 3. userForm.jsp and success.jsp
userForm.jsp is the form where you enter the User Name and Department 

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>

<html:form action="/saveUser.do" method="post">
User Name : <html:text property="userName" size="30" maxlength="120"/> <br>
Department : <html:text property="deptName" size="30" maxlength="120"/> <br>
<html:submit>Save</html:submit> </html:form> 

success.jsp 
<h2>User Data saved </h2>
com.UserSaveAction.java
UserSaveAction get the user entered information (RequestProcessor set the user entered data into the UserForm). Get the service from applicationContext.xml using 
UserService userservice = (UserService) ServiceFinder.getContext(request) .getBean("userservice"); 
In the Action class just get the data from UserForm and call to userservice.saveUser(userbean);
package com;

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;

public class UserSaveAction extends Action{

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{

UserService userservice = (UserService) ServiceFinder.getContext(request)
.getBean("userservice");

UserForm userForm = (UserForm) form;
UserBean userbean = new UserBean();
userbean.setUserName(userForm.getUserName());
userbean.setDeptName(userForm.getDeptName());
userservice.saveUser(userbean);

return mapping.findForward("success");
}
}

com.UserForm.java
UserForm is the Form which contain the entered user information.
(RequestProcessor set the user entered data into the UserForm). 
package com;

import org.apache.struts.action.ActionForm;
public class UserForm extends ActionForm{
String userName;
String deptName;
/**
* @return Returns the deptName.
*/
public String getDeptName() {
return deptName;
}
/**
* @param deptName The deptName to set.
*/
public void setDeptName(String deptName) {
this.deptName = deptName;
}
/**
* @return Returns the userName.
*/
public String getUserName() {
return userName;
}
/**
* @param userName The userName to set.
*/
public void setUserName(String userName) {
this.userName = userName;
}
}

Spring Part 

Step 1. Add ContextLoaderServlet in web.xml
ContextLoaderServlet

ContextLoaderServlet register an ApplicationContext using the the below configuration in web.xml file. 
You can get any service (Defind in applicationContext.xml) using request.getSession().getServletContext().getBean("userservice"); 

<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Step 2. applicationContext.xml 
applicationContext.xml contains all the Dependency Injections . And it contains hibernate SessionFactory information also. Here Hibernate integatred with Spring. 
userservice object has userdao object as setter Injection 
userdao object has sessionFactory object as setter Injection.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://localhost:3306/techfaq</value></property>
<property name="username"><value>techfaq</value></property>
<property name="password"><value>techfaq</value></property>

</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref bean="myDataSource"/></property>
<property name="mappingResources">
<list>
<value>/com/user.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean> 

<bean id="userdao" class="com.UserDAO">
<property name="sessionFactory"><ref bean="mySessionFactory"/></property>

</bean>

<bean id="userservice" class="com.UserService">
<property name="userdao"><ref bean="userdao"/></property>
</bean>
</beans>


com.UserService.java
package com;
public class UserService {
private UserDAO userdao;

public void saveUser(UserBean user){
getUserdao().saveUser(user);
}

/**
* @return Returns the userdao.
*/
public UserDAO getUserdao() {
return userdao;
}
/**
* @param userdao The userdao to set.
*/
public void setUserdao(UserDAO userdao) {
this.userdao = userdao;
}
}

com.ServiceFinder.java
package com; 
import org.springframework.context.ApplicationContext; 

import org.springframework.web.context.support.WebApplicationContextUtils; 
import javax.servlet.ServletRequest; 
import javax.servlet.http.HttpServletRequest; 
public class ServiceFinder { 
public static ApplicationContext getContext(HttpServletRequest httpRequest) {
return WebApplicationContextUtils.getRequiredWebApplicationContext(
httpRequest.getSession().getServletContext()); 
} 
} 


Hibernate Part 
Step 1. Create Table in Data Base

CREATE TABLE `techfaq`.`user_test` 
( `user_id` int(10) unsigned NOT NULL auto_increment,
`user_name` varchar(45) default NULL,
`dept_name` varchar(45) default NULL, 
PRIMARY KEY (`user_id`));

Step 2. user.hbm.xml which maps to user_test TABLE
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.UserBean" table="USER_TEST">
<id name="userId" column="USER_ID" type="int">
<generator class="native"/>
</id>
<property name="userName" column="user_name"/>
<property name="deptName" column="dept_name"/>

</class>
</hibernate-mapping>

Step 3. UserBean.java which maps to user.hbm.xml and user_test TABLE
package com;
public class UserBean {
int userId;
String userName;
String deptName;

public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}

Step 4. UserDAO.java which is used to save user details into Data Base
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;

public class UserDAO {

private SessionFactory sessionFactory;
public void saveUser(UserBean user){
Session session = getSessionFactory().openSession();
try {
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
}
catch(Exception e){e.printStackTrace();}
finally{session.close();}
}

public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}

No comments:

Post a Comment