Spring+SpringMVC+MyBatis 整合

前言

  主角即Spring、SpringMVC、MyBatis,即所谓的SSM框架,大家应该也都有所了解,概念性的东西就不写了,有万能的百度。之前没有记录SSM整合的过程,这次刚刚好基于自己的一个小项目重新搭建了一次,而且比项目搭建的要更好一些。以前解决问题的过程和方法并没有及时记录,以后在自己的小项目中遇到我再整理分享一下。个人认为使用框架并不是很难,关键要理解其思想,这对于我们提高编程水平很有帮助。 

  工作环境:JDK 1.7、Mysql 5.6、Myeclipse 10、Tomcat 7、Maven

  框架版本:Spring 4.2.6.RELEASE、SpringMVC 4.2.6.RELEASE、MyBatis 3.2.8

  

一、整体文件结构设计

项目目录结构:

      Spring+SpringMVC+MyBatis 整合_第1张图片

 

  1、类文件和资源文件分开存放,类文件分为六层,其中common存放公共和框架部分,controller存放项目控制层,service存放项目业务逻辑层,model存放项目实体类,mapper存放数据层接口,test存放测试相关类。

  注:若涉及到多业务模块的情况,分层可以在各层内部进行划分,当然对于大模块建议采用Maven多模块项目方式搭建。

  2、前端在webapp下分出了common和project,common存放公共部分,project内部用于存放多个子模块,common以及各子模块内部分别新建images,js,css和view四个文件夹,用于归类不同资源。

 

二、项目入口web.xml

  构建好整体结构后,接下来应该把目光看下web.xml文件,无论是何种JavaEE框架,入口总是在web.xml,认准这边就没错了。

  web.xml 内容很多,SSM整合相关的关键部分就是加载Spring配置文件spring-config.xml,以及将SpringMVC核心调度器DispatcherServlet注册为servlet(配置文件为mvc-config.xml),其他部分有注释,选择性观看即可。

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_3_0.xsd" version="3.0">
  
     
    <display-name>SpringMVCdisplay-name>
    <description>柴可夫斯基模板description>
      <icon>
         <small-icon>/common/images/favicon.icosmall-icon>
       <large-icon>/common/images/favicon.icolarge-icon>
    icon>
  
    
    

      
    <context-param>  
        <param-name>webAppRootKeyparam-name>  
        <param-value>spring4.rootparam-value>  
    context-param> 
    
     
    
     
    
     
    
    <context-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath*:spring-config.xmlparam-value>
      
    context-param>
    
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    
    
    
    <listener>
      <listener-class>com.demo.common.startup.InitListenerlistener-class>
    listener>
    
    
    <listener>
      <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
    listener>
    
    
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListenerlistener-class>
    listener>
    
     
    <filter>
      <filter-name>characterEncodingFilterfilter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
      <init-param>
        <param-name>encodingparam-name>
        <param-value>UTF-8param-value>
      init-param>
      <init-param>
        <param-name>forceEncodingparam-name>
        <param-value>trueparam-value>
      init-param>
    filter>
    <filter-mapping>
      <filter-name>characterEncodingFilterfilter-name>
      <url-pattern>/*url-pattern>
    filter-mapping>
  
    
    <filter>
      <filter-name>loginFilterfilter-name>
      <filter-class>com.demo.common.filter.LoginFilterSpringfilter-class>
      <init-param>
        <param-name>charsetparam-name>
        <param-value>UTF-8param-value>
      init-param>
      <init-param>
        <param-name>contentTypeparam-name>
        <param-value>text/html;charset=UTF-8param-value>
      init-param>
    filter>
    <filter-mapping>
      <filter-name>loginFilterfilter-name>
      <url-pattern>*.jspurl-pattern>
    filter-mapping>
    
    
    <filter>
        <filter-name>wrapRequestFilterfilter-name>
        <filter-class>com.demo.common.filter.WrapParameterFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>wrapRequestFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
      
    <servlet-mapping>
      <servlet-name>defaultservlet-name>
      <url-pattern>*.jpgurl-pattern>
      <url-pattern>*.gifurl-pattern>
      <url-pattern>*.pngurl-pattern>
      <url-pattern>*.jsurl-pattern>
      <url-pattern>*.cssurl-pattern>
      <url-pattern>*.icourl-pattern>
      <url-pattern>*.eoturl-pattern>
      <url-pattern>*.svgurl-pattern>
      <url-pattern>*.ttfurl-pattern>
      <url-pattern>*.woffurl-pattern>
      <url-pattern>*.mp3url-pattern>
      <url-pattern>*.htmlurl-pattern>
    servlet-mapping>
    
    
    
    
    
    <servlet>
      <servlet-name>SpringMVCservlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
      <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath*:mvc-config.xmlparam-value>
      init-param>
      <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
      <servlet-name>SpringMVCservlet-name>
      <url-pattern>/url-pattern>
    servlet-mapping>
    
     
    <servlet>
      <servlet-name>initServletservlet-name>
      <servlet-class>com.demo.common.startup.InitServletservlet-class>
      <load-on-startup>0load-on-startup>
    servlet>
    
    
    
    <servlet>
      <servlet-name>DruidStatViewservlet-name>
      <servlet-class>com.alibaba.druid.support.http.StatViewServletservlet-class>
      <init-param>
            <param-name>allowparam-name>
            <param-value>127.0.0.1param-value>
        init-param>
    servlet>
    <servlet-mapping>
      <servlet-name>DruidStatViewservlet-name>
      <url-pattern>/druid/*url-pattern>
    servlet-mapping>
    
    
    <servlet>
        <servlet-name>CXFServiceservlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServletservlet-class>
        <load-on-startup>1load-on-startup> 
    servlet>
    <servlet-mapping>
        <servlet-name>CXFServiceservlet-name>
        <url-pattern>/webservice/*url-pattern>
    servlet-mapping>
    
    
    <session-config>
      <session-timeout>60session-timeout>
    session-config>
    
    
    <error-page>
      <error-code>404error-code>
      <location>/common/view/404.jsplocation>
    error-page>
    <error-page>
      <error-code>500error-code>
      <location>/common/view/500.jsplocation>
    error-page>
    
    
    <welcome-file-list>
      <welcome-file>common/view/index.jspwelcome-file>
    welcome-file-list>

web-app>
复制代码

 

三、Spring 框架配置

这块涉及内容也很多,从何说起呢,先上一下文件内容好了:

spring-config.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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
    
    
    <context:property-placeholder ignore-unresolvable="true" location="classpath:constant.properties"/>
    
    
    <task:annotation-driven />
    
    
    
    
    
    
    <context:component-scan base-package="com.demo"> 
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    context:component-scan>  
    
    
    <import resource="spring-mybatis.xml"/>
    
    
    <import resource="spring-socket.xml"/>
    
    
    <import resource="test/mongo-config.xml"/>
    
    
    
    
    
    
    
    
    
    
    
    <import resource="test/spring-cxf.xml"/>
    
    
    
beans>
复制代码

上面内容很多,但是并不全是SSM框架的,需要关注的点只有下面几个:

1、context:component-scan 包扫描

  这个注解不用多说了,要注意的就是主容器中不扫描@Controller注解,因为@Controller将会在SpringMVC扫描。

2、import 标签和多文件配置

  在团队开发时候,每个人都常去改动Spring配置文件,不科学,使用这个技巧方便,每个都有各自的配置文件了。项目较大,有较多的bean时,可以将其分散到子文件中。虽然Spring还有自动扫描的功能,但我感觉也不怎么好,需要去扫描,影响性能;而且各个Bean分散在不同包中,不好配置。

  多文件配置通常有两种做法:

  2.1 在 web.xml配置中的contextConfigLocation节点配置多个值。

具体代码如下:

复制代码
<context-param> 
   <param-name>contextConfigLocationparam-name> 
   <param-value> 
      /WEB-INF/classes/context1.xml, 
       /WEB-INF/classes/context2.xml, 
       /WEB-INF/classes/context3.xml    
    param-value> 
context-param> 
复制代码

  其中分隔符可以是","也可以是" "等,也可以用通配符application-*,这样配置的要求是,你的Spring配置文件必须是applicationContext-*****.xml这样的形式存在,*号代表通配符,具体就不说了。 

     2.2 在一个application.xml中配置多个import标签引入其他文件。

  个人喜欢这种方式,清晰明了,总得有一个主入口吧(估计受了webpack和SeaJS的影响)。

  从这边也不难看到Spring框架在其中扮演的角色:管理容器,有效地组织你的中间层对象(无节操得集成其他框架)。

3、引入mybatis配置:spring-mybatis.xml

  这个文件就是用来完成spring和mybatis的整合的。这里面也没多少行配置,主要的就是自动扫描,自动注入,配置数据库。注释也很详细,大家看看就明白了。

spring-mybatis.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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    
    
    <context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties" />
    
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" 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}" />
    
        
        <property name="initialSize" value="10" />  
        <property name="minIdle" value="20" />  
        <property name="maxActive" value="100" />  
        
        
        <property name="maxWait" value="60000" />  
    
        
        <property name="timeBetweenEvictionRunsMillis" value="6000" />  
        
        
        <property name="minEvictableIdleTimeMillis" value="300000" />  
    
        
        <property name="validationQuery" value="SELECT 'x' FROM DUAL" />  
        <property name="testWhileIdle" value="true" />  
        <property name="testOnBorrow" value="false" />  
        <property name="testOnReturn" value="false" /> 
    
          
        <property name="filters" value="stat" />  
    bean> 
    
    
     
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  

        <property name="dataSource" ref="dataSource" >property>    

          
        <property name="typeAliasesPackage" value="com.demo.model" />
        
          
        <property name="typeAliasesSuperType" value="com.demo.common.base.BaseEntity"/>
        
           
         
        <property name="mapperLocations" value="classpath*:mappings/**/*.xml"/>
        
         
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
    bean>  

    
    <bean id="mapperScannerConfigurer"  class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        
        
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

        
        <property name="basePackage" value="com.demo.mapper">property>
    
        
        <property name="annotationClass" value="com.demo.common.persistence.annotation.MyBatisDao"/>
    bean>
    
     
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    
    
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource">bean>
    
beans>
复制代码

 

四、SpringMVC 框架配置

  这块配置里面的注释也很详细,在此就不说了,主要是自动扫描控制器,视图模式,注解的启动这三个。

mvc-config.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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
    
    
    <context:component-scan base-package="com.demo"  use-default-filters="false">      
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />    
    context:component-scan>  
    
      
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8">property>   
        <property name="maxUploadSize" value="2097152">property>   
        <property name="maxInMemorySize" value="40960">property>  
    bean>  
    
      
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            bean>
        mvc:message-converters>
    mvc:annotation-driven>
    
    
    <mvc:interceptors>    
      <mvc:interceptor>    
            <mvc:mapping path="/**" />     
            <bean class="com.demo.common.core.SpringMVCInterceptor">bean>    
        mvc:interceptor>    
    mvc:interceptors>    
    
    
     
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/project/" p:suffix=".jsp" />
        
beans>
复制代码

  这部分内容也可以参考上一篇博文:《经久不衰的Spring框架:SpringMVC 统括》

 

五、部署与测试

  到此,已经完成了SSM三大框架的整合了,接下来测试一下,如果成功了,那么恭喜你,如果失败了,继续调试吧,作为程序员就是不停的与BUG做斗争!

    测试的话,无非就是新建对应的view、controller、service、mapper ,测试一下SpringMVC和Mybatis的功能,很简单,就不罗嗦了。

  部署的话,就干到tomcat里面去,启动,访问localhost即可,也不赘述了。

  至此,SSM三大框架的整合就完成了,在此基础上可再添加其他功能。

 

你可能感兴趣的:(java)