Struts2.3.28+spring4.1.6+hibernate4.3.8整合总结(注解)

以前一直听说s2sh整合开发项目,也用过一些在网上找到过一下配置好的整合实例进行过测试,测试的例子在我的csdn上面

注解方式:http://download.csdn.net/detail/mjcreator/9523091

xml文件方式:http://download.csdn.net/detail/mjcreator/9523113

但是,一直比较好奇我自己是否能够自己来整合一下这几个框架,于是乎今天耗费了我几个小时还是把s2sh整合好了。

好吧,下面总结一下这个整合吧。

1.首先一个肯定是导入jar包啦,我导入jar包的思路是将每个框架各自的jar包分别导入到项目中

1).struts2:直接使用app里面blank下的jar包导入即可,这里就不详细描述了

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:项目目录\hibernate-release-4.3.8.Final\lib\required这里面的jar包全部导入进来即可。

到这里3个框架的jar包基本上是导入进来了,但是这并不代表整个整合就完了,相信这个时候你些好配置文件,测试代码启动项目茫茫多的异常会跟随而来。

4)其他jar包的介绍:

扫描二维码关注公众号,回复: 277474 查看本文章

a.mysql-connector-java-3.1.13-bin.jar:这个包就不多说了,数据库的包,如果不想操作mysql数据库,这个jar包或许可以不要。

b.slf4j的包,我这里包括slf4j-api-1.5.8.jar,slf4j-log4j12-1.5.8.jar这两个包。

slf4j是日志文件接口的包,我在网上看到的说法是使用这个来进行日志管理,在以后更换具体实现的日志管理方式的时候可以尽可能少的改动代码,看这个就有点像jpa跟hibernate之间的关系一样了。

c.commons-pool.jar:这个包网上的说法是为了是配置数据池连接用的,一般少了这个包在我的这个项目中会提示:

Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool.impl.GenericObjectPool这个异常。

d.commons-dbcp-1.2.1.jar:这个jar包主要是为注入dataSource而来的,具体的代码如下:

<!-- 数据库驱动的配置 -->
	<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>

注意这里的dataSource注入方式,导入commons-dbcp-1.2.1.jar使用org.apache.commons.dbcp.BasicDataSource这只是其中一种注入方法,其他的方法以后再总结吧 

e.额,好吧,差点又忘记一个非常重要非常重要的包了,这个包就是struts2-spring-plugin-2.3.28.jar,struts2与spring关系管理的一个jar包吧,少了这个包是万万行不通的,当然这个jar包肯定要根据具体的struts2的版本在struts2中找这个包,我这里的struts2的版本是2.3.28.

好吧,到这里基本上所有的jar包都导入进去的话就可以进行开发了,在开发之前再提几个我在这次整合过程中遇到的问题吧。

1.hibernate3与hibernate4之前的问题。

在整合过程中我是用的hibernate4进行整合,但是在applicationContext.xml文件中注入hibernateTemplate时使用的是org.springframework.orm.hibernate3.HibernateTemplate以及在注入transactionManager时使用org.springframework.orm.hibernate3.HibernateTransactionManager,这样的配置会导致一定的冲突导致异常,解决办法:只需要将hibernate3修改成hibernate4即可。还有org.springframework.orm下面的hibernate3与hibernate4是有一些差异的,在使用的时候注意一下吧。

还有,使用hibernate4的时候使用注解与使用xml文件配置注入sessionFactory都是使用的org.springframework.orm.hibernate4.LocalSessionFactoryBean,

但是hiberante3就有一点差别,hibernate3注解使用org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean,而xml使用的是

org.springframework.orm.hibernate3.LocalSessionFactoryBean

好吧,先这样吧,下面将这个项目测试的代码帖在这里吧。

1.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" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 这里指定spring主配置文件的位置 -->
    <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.applicationContext.xml文件的配置:

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


	<!-- 启动注解扫描器 -->
	<context:component-scan base-package="cn.s2sh.demo"></context:component-scan>
	<!-- 数据库配置文件读取 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
	<!-- 数据库驱动的配置 -->
	<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配置 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- annotatedPackages 不可用, packagesToScan 版本2.5.6才会有 -->
		<property name="annotatedClasses">
			<list>
				<value>cn.s2sh.demo.model.User</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<!-- 配置时前面最好添加上 'hibernate.' -->
				<!-- 一个Hibernate Dialect类名允许Hibernate针对特定的关系数据库生成优化的SQL -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<!-- 输出所有SQL语句到控制台 -->
				<prop key="hibernate.show_sql">true</prop>
				<!-- 在log和console中打印出更漂亮的SQL -->
				<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>
	<!-- 声明注解方式事务管理器 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

3.jdbc.properties文件的配置:

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.struts.xml文件的配置:

<?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>
	<!-- 把struts的请求委托给spring管理,
           作用:创建Action实例的过程由spring处理,其他的还是由struts2自己处理 -->
   <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类:

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

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接口:

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

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接口:

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

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>

 部署到tomcat上启动项目,访问http://localhost:8080/s2sh-annotation-test/user.jsp即可进行测试。

我这里新增跟查询都跳转到index.jsp页面上,只要点击跳转到index.jsp页面即表示成功了。

项目完整内容保存在csdn上面,访问地址:http://download.csdn.net/detail/mjcreator/9525335

猜你喜欢

转载自forsave.iteye.com/blog/2299292
今日推荐