Struts2.3.28+spring4.1.6+hibernate4.3.8 integration summary (annotation)

I have always heard about the s2sh integration development project before, and I have also used some configured integration instances that I have found on the Internet and tested them. The test examples are on my csdn.

Annotation method: http://download.csdn.net/detail/mjcreator/9523091

xml file method: http://download.csdn.net/detail/mjcreator/9523113 .

However, I have always been curious about whether I can integrate these frameworks myself, so it took me a few hours today to integrate s2sh.

Well, let’s summarize the integration below.

1. The first one is to import the jar package. My idea of ​​importing the jar package is to import the respective jar packages of each framework into the project.

1).struts2: You can directly use the jar package under blank in the app to import it. It will not be described in detail here.

2).spring:aopalliance-1.0.jar,aspectjweaver.jar,cglib-nodep-2.1_3.jar,commons-logging-1.1.3.jar,spring-aop-4.1.6.RELEASE.jar,spring-aspects-4.1.6.RELEASE.jar,spring-beans-4.1.6.RELEASE.jar,spring-context-4.1.6.RELEASE.jar,spring-core-4.1.6.RELEASE.jar,spring-expression-4.1.6.RELEASE.jar,spring-jdbc-4.1.6.RELEASE.jar,spring-orm-4.1.6.RELEASE.jar,spring-tx-4.1.6.RELEASE.jar,spring-web-4.1.6.RELEASE.jar。

3). Hibernate: All the jar packages in the project directory \hibernate-release-4.3.8.Final\lib\required can be imported.

At this point, the jar packages of the three frameworks are basically imported, but this does not mean that the whole integration is over. I believe that you have some good configuration files at this time, and the numerous exceptions of the test code startup project will follow.

4) Introduction of other jar packages:

a.mysql-connector-java-3.1.13-bin.jar: I won't say much about this package, the database package, if you don't want to operate the mysql database, this jar package may not be needed.

The package of b.slf4j, I include the two packages slf4j-api-1.5.8.jar and slf4j-log4j12-1.5.8.jar here.

slf4j is the log file interface package. I saw on the Internet that it is used for log management. When changing the specific log management method in the future, you can change the code as little as possible. It is a bit like jpa and hibernate. The relationship is the same.

c.commons-pool.jar: This package is said on the Internet to configure the data pool connection . Generally, if this package is missing, it will prompt in my project:

Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool.impl.GenericObjectPool this exception.

d.commons-dbcp-1.2.1.jar: This jar package is mainly for injecting dataSource. The specific code is as follows:

 

<!-- Database driven configuration -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<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>

 

Pay attention to the dataSource injection method here, import commons-dbcp-1.2.1.jar and use org.apache.commons.dbcp.BasicDataSource This is just one of the injection methods, and other methods will be summarized later 

e. Well, well, I almost forgot a very important and very important package. This package is struts2-spring-plugin-2.3.28.jar, a jar package for relationship management between struts2 and spring. Without this package, it is It will never work. Of course, this jar package must be found in struts2 according to the specific version of struts2. The version of struts2 here is 2.3.28.

Well, if basically all the jar packages are imported here, development can be carried out. Before development, let me mention a few problems I encountered during this integration process.

 

 

 

1. The problem before hibernate3 and hibernate4.

 

During the integration process, I used hibernate4 for integration, but I used org.springframework.orm.hibernate3.HibernateTemplate when injecting hibernateTemplate in the applicationContext.xml file and org.springframework.orm.hibernate3.HibernateTransactionManager when injecting transactionManager , Such a configuration will cause certain conflicts and cause exceptions. The solution: just change hibernate3 to hibernate4. There are also some differences between hibernate3 and hibernate4 under org.springframework.orm, please pay attention when using them.

Also, when using hibernate4, using annotations and using xml file configuration to inject sessionFactory both use org.springframework.orm.hibernate4.LocalSessionFactoryBean,

But hiberante3 is a little different, hibernate3 annotation uses org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean, and xml uses

org.springframework.orm.hibernate3.LocalSessionFactoryBean

Well , let’s do this first, and post the code for this project test here.

1. Configuration of the web.xml file:

 

<?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" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- Here specifies the location of the spring main configuration file-->
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 2. Configuration of the applicationContext.xml file:

 

 

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">


	<!-- start annotation scanner-->
	<context:component-scan base-package="cn.s2sh.demo"></context:component-scan>
	<!-- Database configuration file read-->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
	<!-- Database driven configuration -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<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>
	<!-- sessionFactory configuration-->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- annotatedPackages not available, packagesToScan version 2.5.6 will have -->
		<property name="annotatedClasses">
			<list>
				<value>cn.s2sh.demo.model.User</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<!-- It is best to add 'hibernate.' in front of the configuration -->
				<!-- A Hibernate Dialect class name that allows Hibernate to generate optimized SQL for a specific relational database -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<!-- Output all SQL statements to the console -->
				<prop key="hibernate.show_sql">true</prop>
				<!-- Print prettier SQL in log and console -->
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>
	<!-- Declare annotation mode transaction manager-->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

3. Configuration of the jdbc.properties file:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/item?useUnicode\=true&characterEncoding\=utf-8&autoReconnect\=true
jdbc.username=root
jdbc.password=123456

4. Configuration of struts.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
	"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
	<!-- Delegate struts requests to spring management,
           Function: The process of creating an Action instance is handled by spring, and the rest is handled by struts2 itself -->
   <constant name="struts.objectFactory" value="spring" />
   
   <package name="default" namespace="/" extends="struts-default">
   		<action name="userAdd" class="cn.s2sh.demo.controller.UserController" method="add">
   			<result name="success">/index.jsp</result>
   		</action>
   		<action name="userQuery" class="cn.s2sh.demo.controller.UserController" method="query">
   			<result name="success">/index.jsp</result>
   		</action>
   </package>
</struts>

5. UserController class:

package cn.s2sh.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import cn.s2sh.demo.model.User;
import cn.s2sh.demo.service.intf.UserService;

import com.opensymphony.xwork2.ActionSupport;

@Controller
public class UserController extends ActionSupport{

	private User user;
	@Autowired(required=true)
	private UserService userService;
	public String add() {
		this.userService.add(user);
		return SUCCESS;
	}

	public String query() {
		this.userService.query();
		return SUCCESS;
	}
	
	
	public UserService getUserService() {
		return userService;
	}


	public void setUserService(UserService userService) {
		this.userService = userService;
	}


	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	
}

 6.User class:

package cn.s2sh.demo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * User entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "t_user")
public class User implements java.io.Serializable {
	// Fields
	private int id;
	private String name;
	private int age;
	
	// Constructors
	/** default constructor */
	public User() {
	}


	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	@Column(name = "name", length = 20)
	public String getName() {
		return this.name;
	}


	public void setName(String username) {
		this.name = username;
	}
	@Column(name="age",length=3)
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

7. UserService interface:

package cn.s2sh.demo.service.intf;

import java.util.List;

import cn.s2sh.demo.model.User;

public interface UserService {

	public void add(User user);
	
	public List<User> query();
}

8. UserServiceImpl class:

package cn.s2sh.demo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.s2sh.demo.dao.intf.UserDao;
import cn.s2sh.demo.model.User;
import cn.s2sh.demo.service.intf.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired(required=true)
	private UserDao userDao;
	
	@Override
	public void add(User user) {
		this.userDao.add(user);

	}
	
	@Override
	public List<User> query() {
		return this.userDao.query();
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	

}

 9.UserDao interface:

package cn.s2sh.demo.dao.intf;

import java.util.List;

import cn.s2sh.demo.model.User;

public interface UserDao {

	public void add(User user);
	
	public List<User> query() ;
}

10. UserDaoImpl class:

package cn.s2sh.demo.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.s2sh.demo.dao.intf.UserDao;
import cn.s2sh.demo.model.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao{

	@Autowired(required=true)
	private HibernateTemplate hibernateTemplate;
	
	@Transactional(readOnly=false)
	@Override
	public void add(User user) {
		this.hibernateTemplate.save(user);
	}

	@Override
	public List<User> query() {
		List<User> userList = (List<User>)this.getHibernateTemplate().find("select u.name from User u ");
		System.out.println(userList);
		return userList;
	}
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	
}

 11.index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>

12.user.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  		<form action="userAdd" method="post">
  			姓名:<input type="text" name="user.name"/>
  			年龄:<input type="text" name="user.age"/>
  			<input type="submit" value="submit" />
  		</form>
  		<a href="userQuery">query</a>
  </body>
</html>

 Deploy to tomcat to start the project and visit http://localhost:8080/s2sh-annotation-test/user.jsp to test.

I am here to add and query to jump to the index.jsp page, as long as you click to jump to the index.jsp page, it means success.

The complete content of the project is saved on csdn, and the access address is: http://download.csdn.net/detail/mjcreator/9525335

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326581500&siteId=291194637