Spring 4 + Struts 2 + Hibernate 4 Annotation Integration Example using JavaConfig

By Arvind Rai, October 08, 2015
This page will provide Spring 4 + Struts 2 + Hibernate 4 annotation integration example using JavaConfig. Hibernate is integrated with spring and we get hibernate template to perform our database task. In our demo, we are using JavaConfig where we are configuring datasource for MySQL. To integrate spring with struts 2, we need to perform two steps in web.xml. First we will configure two context parameter that will allow to register annotation based spring JavaConfig and second is ContextLoaderListener. In action classes we can inject spring beans by autowiring. Find the complete example.

Software Used in Demo

Find the software used in the example.
1. Java 8
2. Tomcat 8
3. MySQL 5.1
4. Spring 4.1
5. Struts 2
6. Hibernate 4
7. Gradle
8. Eclipse

Project Structure in Eclipse

Find the project structure in eclipse.
Spring 4 + Struts 2 + Hibernate 4 Annotation Integration Example using JavaConfig

build.gradle

Find build.gradle file. Struts 2 provides struts2-spring-plugin jar that helps to integrate Spring with struts 2.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'Spring4'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.2.3.RELEASE'
    compile 'org.springframework:spring-web:4.1.6.RELEASE'
    compile 'org.apache.struts:struts2-core:2.5-BETA2'
    compile 'org.apache.struts:struts2-convention-plugin:2.5-BETA2'
    compile 'org.apache.struts:struts2-spring-plugin:2.5-BETA2'
    compile 'org.hibernate:hibernate-core:4.3.6.Final'
    compile 'javax.servlet:javax.servlet-api:3.1.0'
    compile 'org.slf4j:slf4j-simple:1.7.7'
    compile 'org.javassist:javassist:3.15.0-GA'
    compile 'mysql:mysql-connector-java:5.1.31'
    compile 'commons-dbcp:commons-dbcp:1.4'
}  

Table Used

Find the table schema used in demo.
Table Schema: userdetail
CREATE TABLE `userdetail` (
	`id` INT(10) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NULL DEFAULT NULL,
	`email` VARCHAR(50) NULL DEFAULT NULL,
	`age` INT(10) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB; 

JavaConfig for Spring with Hibernate Integration

Find the JavaConfig for spring. Here we are writing code to integrate hibernate and spring using MySQL.
AppConfig.java
package com.concretepage.config;  
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.concretepage.persistence.User;
@Configuration 
@ComponentScan("com.concretepage")
@EnableTransactionManagement
public class AppConfig {  
	@Bean
	public HibernateTemplate hibernateTemplate() {
		return new HibernateTemplate(sessionFactory());
	}
	@Bean
	public SessionFactory sessionFactory() {
		return new LocalSessionFactoryBuilder(getDataSource())
		   .addAnnotatedClasses(User.class)
		   .buildSessionFactory();
	}
	@Bean
	public DataSource getDataSource() {
	    BasicDataSource dataSource = new BasicDataSource();
	    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	    dataSource.setUrl("jdbc:mysql://localhost:3306/concretepage");
	    dataSource.setUsername("root");
	    dataSource.setPassword("");
	    return dataSource;
	}
	@Bean
	public HibernateTransactionManager hibTransMan(){
		return new HibernateTransactionManager(sessionFactory());
	}
} 

web.xml with Spring and Struts 2 Integration

In web.xml, we will perform two steps to intergrate spring.
Step 1. To refer spring JavaConfig, we need to use two context parameter as following.
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.concretepage.config.AppConfig</param-value>
  </context-param>
  <context-param>
    <param-name>contextClass</param-name>
    <param-value>
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
  </context-param> 

Step 2. Register ContextLoaderListener.
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 
Find the web.xml.
web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <display-name> Spring 4 + Struts 2 + Hibernate 4 Integration </display-name>
  <context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>com.concretepage.config.AppConfig</param-value>
  </context-param>
  <context-param>
    <param-name>contextClass</param-name>
    <param-value>
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
  </context-param>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.concretepage.action</param-value>
        </init-param>
  </filter>
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app> 

DAO Class


UserDao.java
package com.concretepage.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.concretepage.persistence.User;
@Service
@Transactional(readOnly = false)
public class UserDao {
  @Autowired	
  HibernateTemplate template;	
  public void saveUserDetail(User user){
	    template.save(user);
	    System.out.println("done");
  }
} 

User.java
package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="userdetail")
@Entity
public class User implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="id")
	private int id;
	@Column(name="name")
	private String name;
	@Column(name="email")
	private String email;
	@Column(name="age")
	private int age;
	public User(String name, String email,int age){
		this.name = name;
		this.email = email;
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}  

Struts 2 Action Classes

Find the struts 2 action classes. To inject DAO classes by spring, we will autowire.
ResultAction.java
package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.springframework.beans.factory.annotation.Autowired;
import com.concretepage.dao.UserDao;
import com.concretepage.persistence.User;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@ResultPath(value="/")
@Action(value="result", results={@Result(name="success",location="result.jsp")})
public class ResultAction extends ActionSupport{
	@Autowired
	private UserDao userDao;
	private static final long serialVersionUID = 1L;
	private String name;
	private String email;
	private int age;
	public String execute() {
	   User user = new User(name, email, age);	
	   userDao.saveUserDetail(user);
	   return SUCCESS; 
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
} 

UserAction.java
package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@Action("/userform")
@ResultPath(value="/")
@Result(name="success",location="userform.jsp")
public class UserAction extends ActionSupport{
	public String execute() {
	    return SUCCESS;
	}
} 

JSP Files

Find the JSP files.
userform.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Spring 4 + Struts 2 + Hibernate 4 Integration</title>
</head>
<body>
<h1>Spring 4 + Struts 2 + Hibernate 4 Integration</h1>
<s:form action="result" validate="true" >
	<s:textfield name="name" label="Name"/>
	<s:textfield name="email" label="Email"/>
	<s:textfield name="age" label ="Age"/>
	<s:submit method="execute"/>
</s:form>
</body>
</html> 

result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><head><title> Spring 4 + Struts 2 + Hibernate 4 Integration </title>
</head>
<body>
<h1>User detail saved successfully.</h1>
</body>
</html> 

Output

Spring 4 + Struts 2 + Hibernate 4 Annotation Integration Example using JavaConfig

User detail is inserted into database.
Spring 4 + Struts 2 + Hibernate 4 Annotation Integration Example using JavaConfig

References

Apache Struts 2: Spring Plugin

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us