您的位置:首页 > 编程语言 > Java开发

Spring+Struts2+mybatis 整合(详细解释+完整流程)

2015-08-13 16:12 633 查看
一.新建maven项目 选择 maven-archetype-webApp

二.目录结构规范






三.导入JAR包.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">   <modelVersion>4.0.0</modelVersion>
  <groupId>com.hyycinfo.testssm</groupId>
  <artifactId>ssm1</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ssm1 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
  
  
   <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.4</version>
		</dependency>
		<!-- spring-jdbc: 支持事务处理.. -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.1.4.RELEASE</version>
		</dependency>
		<!-- 数据联接池 : 其它的还有 c3p0 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>20030825.184428</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>20030825.183949</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>20040616</version>
		</dependency>
		<!-- 数据库驱动.. -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>
		<!-- 因为使用了 javax.annotation包中的注解。 -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation</artifactId>
			<version>1.1.0.v201105051105</version>
		</dependency>
    <!-- mybatis -->
    <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.3.0</version>
</dependency>
    
    <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.2.2</version>
</dependency>

<!-- Struts2核心 -->
<dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-core</artifactId>
  <version>2.3.20</version>
</dependency>

<dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-json-plugin</artifactId>
  <version>2.3.20</version>
</dependency>
<!-- 发布的时候不需要 -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>3.0-alpha-1</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.2.1-b03</version>
   <scope>provided</scope>
</dependency>
<!-- spring整合struts2的包 -->
<dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-spring-plugin</artifactId>
  <version>2.3.20</version>
</dependency>
<!-- 提供一个a s r -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>4.1.4.RELEASE</version>
</dependency>

    
  </dependencies>
  <build>
    <finalName>ssm1</finalName>
  </build>
</project>


四.开始配置配置文件
web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" 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"> <!-- 配置一个全局变量,指定spring配置文件的位置 -->

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

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:beans*.xml</param-value>
	</context-param>
	
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

  <welcome-file-list>
    <welcome-file>add.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>


ContextLoaderListener的作用就是启动Web容器时,自动加载<context-param>里配置的匹配beans*.xml的信息,我这里符合的有beans.xml(用于spring配置)和bean-web.xml(用于配置Action)。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
加上启动spring的监听器,这样配置在xml文件中的bean才会初始化

然后开始读取beans.xml配置信息,如下:

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

	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd          http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx.xsd          ">
	<!-- 开启注解 -->
	<context:annotation-config />

 <!-- 先配置扫描包,为了你的系统能够识别相应的注解。该包下的子类也都可以被扫描,另外可以配置不包含的类,详细请另外查看。。
如果想使用@Autowired</span></strong>注解,需要在Spring容器中声明AutowiredAnnotationBean
同理,注解越多,需要在spring容器其中声明的...Bean越多,配置了这个以后,就能让spring自动识别-->
       <context:component-scan base-package="com.hyycinfo" />

 <!--使用注解支持事务,即可以用@Transactional 该方法开启事务 -->
	 <tx:annotation-driven transaction-manager="txManager"/>

<p><!-- 使用spring自带的属性文件读取类完成读取db.properties配置文件的操作 --></p><p><bean id="pphc"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"></p><p><property name="locations" value="classpath:db.properties" /></bean></p><p><!-- 配置dbcp数据源... 数据库联接池 ( jndi-> tomcat的数据库联接池 ) / c3p0 --></p><p><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"></p><p>    <property name="driverClassName" value="${jdbc.driverClassName}" /></p><p>    <property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /></p><p>   <property name="password" value="${jdbc.password}" /></p><p>   <property name="maxActive" value="${jdbc.maxActive}" /></p><p>   <property name="minIdle" value="${jdbc.minIdle}" /></p><p>   <property name="maxIdle" value="${jdbc.maxIdle}" /></p><p></bean></p>
<pre name="code" class="java"><!--下面使针对mybatis的整合配置
	1.sqlsessionfactory
mybatis核心
spring将会在应用启动时为你创 建SqlSessionFactory对象,然后将它以SqlSessionFactory为名来存储
SqlSessionFactory有一个单独的必须属性,就是JDBC的DataSource。这可以是任意的DataSource。其配置应该和其它spring数据库连接是一样的。
一个通用的属性是configLocation,它是用来指定MyBatis的xml配置文件路径的。
 -->
<bean id="SqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"></property>
	<!-- setmapperLocation -->
	<property name="mapperLocations" value="classpath*:com/hyycinfo/ssm1/dao/*.xml"></property>
</bean>

<!-- 配置扫描器,用于扫描所有的mapper文件
如果你使 用了一个 以上的 DataSource ,那 么自动 装配可 能会失效 。
这种 情况下 ,你可 以使用 SqlSessionFactoryBeanName 属性来设置正确的 bean 名 称来使用
这是对spring注解机制的讲解,特别有用 http://blog.163.com/qqabc20082006@126/blog/static/2292852520091128103316534/  -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 配置要扫描的映射文件对应的接口的文件 -->
	<property name="basePackage" value="com.hyycinfo.ssm1.dao"></property>
	<property name="SqlSessionFactoryBeanName" value="SqlSessionFactory"></property>
</bean>

<!-- 1.事物管理器
DataSourceTransactionManager:
此事务管理器是针对传统的JDBC进行事务管理,在spring中是对JdbcTemplate进行事务管理
要 开 启 Spring 的 事 务 处 理 , 在 Spring 的 XML 配 置 文 件 中 简 单 创 建 一 个 DataSourceTransactionManager 对象:
 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
      <!-- 配置增强 -->
    <tx:advice id="txAdvice"  transaction-manager="txManager">
        <!-- 事物语法,切入点,这里加入的是切入点表达式-->
        <tx:attributes>
            <!-- all methods starting with 'get' are read-only -->
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="retrieve*" read-only="true"/>
               <tx:method name="load*" read-only="true"/>
               <tx:method name="datagrid*" read-only="true"/>
            <!-- 其它的方法加上事物-->
              <tx:method name="add*"   propagation="REQUIRED"/>
               <tx:method name="del*"   propagation="REQUIRED"/>
                <tx:method name="update*"   propagation="REQUIRED"/>
                 <tx:method name="modify*"   propagation="REQUIRED"/>
                  <tx:method name="save*"   propagation="REQUIRED"/>
                   <tx:method name="remove*"   propagation="REQUIRED"/>
                    <tx:method name="repair*"   propagation="REQUIRED"/>
                     <tx:method name="insert*"   propagation="REQUIRED"/>
            
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置切面 -->

<!-- ensure that the above transactional advice runs for any execution
        of an operation defined by the FooService interface -->
    <aop:config>
        <aop:pointcut id="service" expression="execution(* com.hyycinfo.ssm1.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
    </aop:config>
    

</beans>


这样配置完毕以后,你可以根据配置文件来知道你接下来要写的类,从上往下:

(1)你需要写一个db.properties数据库链接配置文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm1?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=a
jdbc.maxActive=150
jdbc.minIdle=5
jdbc.maxIdle=20

(2)要扫描的映射文件对应的接口的文件,以及对应的xml映射文件

package com.hyycinfo.ssm1.dao;

import java.util.List;

import com.hyycinfo.ssm1.bean.Student;

public interface StudentDao {
	public int delete (String id);
	public int add(Student student);
	public Student findById(String id);
	public void update(Student student);
}


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.hyycinfo.ssm1.dao.StudentDao">
<resultMap type="com.hyycinfo.ssm1.bean.Student" id="BaseResultMap">
	<id column="id" property="id" jdbcType="CHAR"/>
	<result column="sname" property="sname" jdbcType="VARCHAR"/>
	<result column="age" property="age" />
</resultMap>

<delete id="delete" parameterType="java.lang.String">
	delete from student where id=#{id}
</delete>

<insert id="add" parameterType="com.hyycinfo.ssm1.bean.Student" >
	insert into student(id,sname,age)  values(#{id},#{sname},#{age})
</insert>

<update id="update" parameterType="com.hyycinfo.ssm1.bean.Student">
	update student set sname=#{sname},age=#{age} where id=#{id}
</update>

<select id="findById" resultMap="BaseResultMap" parameterType="java.lang.String">
	select * from student where id=#{id} 
</select>
</mapper>


( 3 ) 业务层

package com.hyycinfo.ssm1.biz;

import com.hyycinfo.ssm1.bean.Student;
import com.hyycinfo.ssm1.dao.StudentDao;

public interface StudentBiz {
	public int delete(String id);
	public int add(Student student);
	public Student  findById(String id);
	public void update(Student student);
	public void setStudentDao(StudentDao studentDao);
}


业务实现类
package com.hyycinfo.ssm1.impl;

import javax.annotation.Resource;

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

import com.hyycinfo.ssm1.bean.Student;
import com.hyycinfo.ssm1.biz.StudentBiz;
import com.hyycinfo.ssm1.dao.StudentDao;
@Service("studentBiz")
public class StudentBizImpl  implements StudentBiz{
	@Autowired
	public StudentDao studentDao;
	
		public int delete(String id){
			return studentDao.delete(id);
		}
		public int add(Student student){
			return studentDao.add(student);
		}
		
		public Student  findById(String id){
			return studentDao.findById(id);
		}
		
		public void update(Student student){
			studentDao.update(student);
			
		}
		public void setStudentDao(StudentDao studentDao){
			this.studentDao=studentDao;
		}
		
}


为了实现你的类,因此你还需要一个bean..

package com.hyycinfo.ssm1.bean;

public class Student {
	private String id;
	private String sname;
	private Integer age;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", sname=" + sname + ", age=" + age + "]";
	}
	public Student(String id, String sname, Integer age) {
		super();
		this.id = id;
		this.sname = sname;
		this.age = age;
	}
	public Student() {
		super();
	}
	
	
}


五.一开始的web.xml提到了我bean*.xml的文件不仅仅只有beans.xml还有bean-web.xml,那么现在加载完beans.xml自然就加载beans-web.xml
这里的beans-web配置的是所有的action,当然你也可以全部配置在beans.xml里面,这样程序会显的臃肿,不清晰

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

	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd          http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx.xsd          ">
 <!-- 为了让控制器Action访问Spring的业务逻辑组件:
 scope="prototype"来保证每一个请求有一个单独的Action来处理,        避免struts中Action的线程安全问题。
这里的ref="studentBiz"由注解注入
 -->
<bean id="studentAction" class="com.hyycinfo.ssm1.web.actions.StudentAction" scope="prototype">
	<property name="studentBiz"  ref="studentBiz"></property>
</bean>
         
         </beans>


然后因为web.xml会自动加载
StrutsPrepareAndExecuteFilter类中
 private static final String DEFAULT_CONFIGURATION_PATHS = "struts-default.xml,struts-plugin.xml,struts.xml";
它会在自动搜索本地的struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.objectFactory" value="spring" />
    <package name="default"  namespace="/" extends="struts-default">
    <!-- 注意:因为这是,由spring来生成action对象
      所以类名是写由spring创建的bean的id,而不是写全路径
     -->
    	<action name="student_*" class="studentAction" method="{1}">
    	<result name="add_success">/add_success.jsp</result>
    	</action>
    </package>
    <!-- Add packages here -->
</struts>


struts.enable.DynamicMethodInvocation ,-动态方法调用,带!感叹号那个。。我也不太熟,但一般禁用
<pre name="code" class="java">devMode  true 开发模式下使用,这样可以打印出更详细的错误信息。

<pre name="code" class="java">objectFactory   spring  该属性指定Struts 2中的Action由Spring容器创建。
这样整个流程就跑完了

为了方便大家,给大家提供了免费代码资源下载http://download.csdn.net/detail/ac_great/9000945

最后提醒大家,以我身边的例子来看,有很多人都整合失败的原因都跟自己的环境有关,比如jdk,tomcat,maven,eclipse平台,还有jar包的原因

这就是最麻烦的地方,所以在做之前一定要确保好自己的环境....

补充一个mysql脚本

create database ssm1;
use ssm1;
drop table if exists student;
create table student(
	id char(50) primary key,
	sname varchar(100) not null,
	age int 
	
)engine=innodb default charset=utf8;
show create table student;
insert into student values('1','张三',22);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: