struts2+spring+mybatis框架搭建

本文介绍了一个使用Struts2、Spring和MyBatis进行整合的项目案例,包括配置文件详解、数据库连接配置、事务管理、Mapper接口定义等内容。

最近要做一个小项目,本来打算用springmvc+spring+mybatis,因为springmvc刚学项目时间又紧所以采用比较熟悉的struts2替代springmvc。

  • 目录结构
    这里写图片描述
  • 需要引用的JAR包 ,我这里用的是struts2-2.1,spring4.3,mybatis3.3版本

    这里写图片描述
    struts2和spring整合需要一个整合插件包struts2-spring-plugin.jar,这里需要说明一下,我最开始用的是struts2-spring-plugin-2.5.5.jar结果出现错误,引起原因是版本兼容性问题,最好与struts2的版本保持一致。

  • 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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>swipe</display-name>

    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-beans.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <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>*.action</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
  • mybatis配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <!-- 开启缓存 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 开启延时加载 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 设置延时时载为按需加载,默认为自动加载,则延时加载没有意义 -->
        <setting name="aggressiveLazyLoading" value="false" />
        <!-- 开启自动驼峰命名规则 -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    <typeAliases>
        <!-- 通过扫描包自动分配别名,如果指定的类有@Alias注解则按注解配置的别名,否则为类名的首字母小写 -->
        <package name="com.csyq.model" />
        <package name="com.csyq.vo" />
        <!-- <typeAlias type="com.csyq.model.CheckInOut" alias="checkInOut"/>
        <typeAlias type="com.csyq.model.Device" alias="device"/>
        <typeAlias type="com.csyq.model.IdCard" alias="idCard"/>
        <typeAlias type="com.csyq.model.Unit" alias="unit"/> -->
    </typeAliases>
    <!-- 与spring集成后 datasource和mapper注册都由spring管理 -->
    <!-- <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
             <property name="url" value="${url}" />
             <property name="username" value="${user}"/>
             <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.csyq.mapper"/>
        <mapper resource="com/csyq/mapper/CheckInOutMapper.xml"/>
        <mapper resource="com/csyq/mapper/DeviceMapper.xml"/>
        <mapper resource="com/csyq/mapper/IdCardMapper.xml"/>
        <mapper resource="com/csyq/mapper/UnitMapper.xml"/>
    </mappers> -->
</configuration>
  • 数据库
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@200.200.200.16:1521:orcl
#用username跟系统名重名,会引起传入值错误
user=swipe
password=1234

initialSize=0
maxActive=20
maxIdle=10
minIdle=1
maxWait=30000
  • spring整合mybatis及基本配置
<?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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!-- 加载数据库配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 扫描并注册  -->
    <context:component-scan base-package="com.csyq.action"></context:component-scan>
    <context:component-scan base-package="com.csyq.service.impl"></context:component-scan>
    <!-- 初始化数据连接  这里用的是DBCP连接池-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="maxIdle" value="${maxIdle}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxWait" value="${maxWait}"/>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 根据方法名指定事务属性 -->
            <!-- propagation="REQUIRES_NEW" 另起新事务 -->
            <tx:method name="get*" read-only="true"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切入点 一般在service层 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.csyq.service.*.*(..))" id="txPointCut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/csyq/mapper/*.xml"></property>
    </bean>
    <!-- 使用这里包扫描的方式 自动创建Mapper的代理对象,实例名为Mapper接口的首字母小写,且Mapper接口和Mapper.xml文件必须在同一个包下,并下文件名相同 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.csyq.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

这里有一点要注意的是,添加事务切入后,启动tomcat会报以下错误

严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener  
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImp' defined in file [E:\javaee\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\scm1.2\WEB-INF\classes\com\hw\service\Imp\UserServiceImp.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0': Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException  
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:452)  
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)  
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)  
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)  

好像是struts与spring有JAR包冲突引起的,需要引入aspectjweaver-1.8.9.jar

  • 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>
    <constant name="struts.i18n.encoding" value="utf-8"></constant>
    <!-- spring整合struts2 -->
    <constant name="struts.objectFactory" value="spring"></constant>

    <package name="user_default" extends="struts-default">
        <!-- 与spring整合后class指定的Action由spring容器生成管理 -->
        <action name="login" method="login" class="loginAction">
            <result name="success">success.jsp</result>
        </action>
    </package>
</struts>
  • Action
    Struts2和Spring整合后, Action实例由spring生成和管理,spring生成对象默认为单例,而Struts2则是每次请求都会生成一个Action,Action是类级别的,参数是成员变量,采用单例模式会引起线程冲突,所以需要将scope改为prototype
@Controller
@Scope("prototype")
public class LoginAction extends BaseAction{

    private UserQueryVo userVo;
    @Autowired
    private UserService userService;
    public String login(){
        return "success";
    }

    public UserQueryVo getUserVo() {
        return userVo;
    }
    public void setUserVo(UserQueryVo userVo) {
        this.userVo = userVo;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
  • Mapper
public interface UserMapper {
    public UserBean getUser(UserQueryVo userVo);
}
  • Mapper.xml
<?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.csyq.mapper.UserMapper">
    <select id="getUser" resultType="userBean" parameterType="userQueryVo">
        select id,name,unitid,mobile from t_user where userid=#{user.userId} and username = #{user.userName}
    </select>
</mapper>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值