Home > Java > javaTutorial > body text

Detailed explanation of Spring, Spring MVC, MyBatis integration file configuration

巴扎黑
Release: 2017-04-30 10:11:39
Original
1899 people have browsed it

I have done several small projects using the SSM framework, and it feels good that it is time to summarize. Let’s first summarize the file configuration of SSM integration. In fact, it is best to read the official documentation for specific usage.

Spring: http://spring.io/docs

MyBatis: http://mybatis.github.io/mybatis-3/

I won’t go into the basic organizational structure and usage. The previous blogs and official documents are very comprehensive. Jar packages can be organized and managed using Maven. Let’s look at the configuration file.

Web.xml configuration

web.xml should be the most important configuration file of the entire project, but servlet3.0 already supports annotation configuration. Before servlet3.0, each servlet must configure the servlet and its mapping relationship in web.xml. But it is not necessary in the spring framework, because Spring is Dependency Injection, also called Inversion of Control. But you also need to configure an important servlet, which is the front-end controller (DispatcherServlet). The configuration method is basically similar to an ordinary servlet.

The configuration content is as follows:

<!-- 配置前端控制器 -->
  <servlet>
      <servlet-name>spring</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <!-- ContextconfigLocation配置springmvc加载的配置文件
          适配器、处理映射器等
           -->
          <param-name>contextConfigLocation</param-name>
          <param-value>WEB-INF/classes/spring/springmvc.xml</param-value>
  </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>spring</servlet-name>
      <!-- 1、.action访问以.action结尾的  由DispatcherServlet进行解析
           2、/,所有访问都由DispatcherServlet进行解析
       -->
      <url-pattern>/</url-pattern>
  </servlet-mapping>
Copy after login

It should be noted here that springmvc.xml is the spring configuration file, which will be discussed later. If the URL in is .action, the front-end controller will only intercept requests ending with .action and ignore static files. Control of static pages requires other means. Using / as the URL will intercept all requests, including requests for static pages. This way you can intercept any request you want to process, but there is a problem. If all requests are intercepted, and if corresponding processing is not done in the interceptor, all static js, css, and images used in the page will be inaccessible and the page will not be displayed normally. But this problem can be solved through the configuration of static resources. Will be mentioned later.

Configure spring container:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/classes/spring/applicationContext-*.xml</param-value>

</context-param>
Copy after login

Among them, applicationContext-*.xml contains 3 configuration files, which are the specific configurations of the springIoC container. Will be mentioned later.

Configure a listener:

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Copy after login

The complete configuration of web.xml is as follows:



      
  
  
  
    404
    /error404.jsp
  
  
  
    500
    /error500.jsp
  
  
  
    
        contextConfigLocation
        WEB-INF/classes/spring/applicationContext-*.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    

    
  <!-- 配置前端控制器 -->
  <servlet>
      <servlet-name>spring</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <!-- ContextconfigLocation配置springmvc加载的配置文件
          适配器、处理映射器等
           -->
          <param-name>contextConfigLocation</param-name>
          <param-value>WEB-INF/classes/spring/springmvc.xml</param-value>
  </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>spring</servlet-name>
      <!-- 1、.action访问以.action结尾的  由DispatcherServlet进行解析
           2、/,所有访问都由DispatcherServlet进行解析
       -->
      <url-pattern>/</url-pattern>
  </servlet-mapping>
    
  
  
      CharacterEncodingFilter
      org.springframework.web.filter.CharacterEncodingFilter
      
          encoding
          utf-8
      
  
  
      CharacterEncodingFilter
      /*
  
  
    welcome.jsp
    
    
Copy after login

See that there are two more pieces of content in the configuration file. One is the error page, which is used to handle errors in a friendly manner. You can use the error code to distinguish and jump to the corresponding processing page. This configuration code is best placed at the front and processed before the front-end controller intercepts it.

Another piece of content is a filter to solve the post garbled problem. It intercepts post requests and encodes them into utf8.

Configuration of springmvc.xml                                                                                                                       View resolver configuration:

<!-- 配置视图解析器 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <!-- 使用前缀和后缀 -->
         <property name="prefix" value="/"></property>
         <property name="suffix" value=".jsp"></property>
</bean>
Copy after login
When setting the view name in the Controller, the prefix and suffix will be automatically added.

Controller configuration

Automatic scanning mode scans all Controllers under the package, and you can use annotations to specify the access path.

<!-- 使用组件扫描的方式可以一次扫描多个Controller -->
<context:component-scan base-package="com.wxisme.ssm.controller">
Copy after login
You can also use a single configuration method, and you need to specify the fully qualified name of the Controller.

<bean name="/queryUser.action" class="com.wxisme.ssm.controller.Controller1"/>
Copy after login
Configure the annotated processor adapter and processor mapper:

<!-- 注解的处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- 注解的处理器映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
Copy after login
You can also use the following simplified configuration:

<!-- 配置注解的处理器映射器和处理器适配器 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
Copy after login
Configure the interceptor, you can directly define to intercept all requests, or you can customize the interception path.

<mvc:interceptors>
    <!-- 直接定义拦截所有请求 -->
    <bean class="com.wxisme.ssm.interceptor.IdentityInterceptor"></bean>
        <!-- <mvc:interceptor>
            拦截所有路径的请求   包括子路径
            <mvc:mapping path="/**"/>
            <bean class="com.wxisme.ssm.interceptor.IdentityInterceptor"></bean>
        </mvc:interceptor> -->
    </mvc:interceptors>
Copy after login
Configure global exception handler

<!-- 定义全局异常处理器 -->
    <!-- 只有一个全局异常处理器起作用 -->
    <bean id="exceptionResolver" class="com.wxisme.ssm.exception.OverallExceptionResolver"></bean>
Copy after login
Configure the file upload data parser, which needs to be configured when uploading files.

<!--配置上传文件数据解析器  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>9242880</value>
        </property>
    </bean>
Copy after login
You can also configure some custom parameter types, taking date type binding as an example.

<!-- 自定义参数类型绑定 -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
     <property name="converters">
         <list>
             <!-- 日期类型绑定 -->
             <bean class="com.wxisme.ssm.controller.converter.DateConverter"/>
         </list>
     </property>
    </bean>
Copy after login
As mentioned above, if all requests are intercepted when configuring the front-end controller, some static resources will become unusable without special processing. If this is the case, you can use the following configuration to access static resource files.

<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/css/**" location="/css/" />  
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/imgdata/**" location="/imgdata/" />
Copy after login
You can also use the default, but it needs to be configured in web.xml.

<!-- 访问静态资源文件 -->
    <!-- <mvc:default-servlet-handler/> 需要在web.xml中配置-->
Copy after login
You can avoid this problem by not intercepting all paths.

The complete configuration is probably like this. You need to pay attention to the namespace of the xml file, which sometimes has an impact.



    
    
     
     
         
         
         
     
     
     
     
     
     
    
    
    <!-- 自定义参数类型绑定 -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
     <property name="converters">
         <list>
             <!-- 日期类型绑定 -->
             <bean class="com.wxisme.ssm.controller.converter.DateConverter"/>
         </list>
     </property>
    </bean>
    
    
    <!-- 访问静态资源文件 -->
    <!-- <mvc:default-servlet-handler/> 需要在web.xml中配置-->
    
    
      
    
    
    
    
    <mvc:interceptors>
    <!-- 直接定义拦截所有请求 -->
    <bean class="com.wxisme.ssm.interceptor.IdentityInterceptor"></bean>
        <!-- <mvc:interceptor>
            拦截所有路径的请求   包括子路径
            <mvc:mapping path="/**"/>
            <bean class="com.wxisme.ssm.interceptor.IdentityInterceptor"></bean>
        </mvc:interceptor> -->
    </mvc:interceptors>
    
    <!--配置上传文件数据解析器  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>9242880</value>
        </property>
    </bean>
    
    <!-- 定义全局异常处理器 -->
    <!-- 只有一个全局异常处理器起作用 -->
    <bean id="exceptionResolver" class="com.wxisme.ssm.exception.OverallExceptionResolver"></bean>
    
 
Copy after login

ApplicationContext-*.xml configuration

                                          

  applicationContext-*.xml包括三个配置文件,分别对应数据层控制、业务逻辑service控制和事务的控制。

  数据访问层的控制,applicationContext-dao.xml的配置:

  配置加载数据连接资源文件的配置,把数据库连接数据抽取到一个properties资源文件中方便管理。

  配置为:

<!-- 加载数据库连接的资源文件 -->
<context:property-placeholder location="/WEB-INF/classes/jdbc.properties"/>
Copy after login

  其中jdbc.properties文件的内容如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/database
jdbc.username=root
jdbc.password=1234
Copy after login

  配置数据库连接池,这里使用的是dbcp,别忘了添加jar包!

<!-- 配置数据源   dbcp数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
Copy after login

  Spring和MyBatis整合配置,jar包由MyBatis提供。

  配置sqlSessionFactory

<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 数据库连接池 -->
    <property name="dataSource" ref="dataSource"/>
    <!-- 加载Mybatis全局配置文件 -->
    <property name="configLocation" value="/WEB-INF/classes/mybatis/SqlMapConfig.xml"/>

</bean>
Copy after login

  SqlMapConfig.xml文件是MyBatis的配置文件,后面会提到。

  配置Mapper扫描器,扫描mapper包下的所有mapper文件和类,要求mapper配置文件和类名需要一致。

<!-- 配置mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 扫描包路径,如果需要扫描多个包中间用半角逗号隔开 -->
    <property name="basePackage" value="com.wxisme.ssm.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
Copy after login

  整个applicationContext-dao.xml配置文件应该是这样的:




<!-- 加载数据库连接的资源文件 -->
<context:property-placeholder location="/WEB-INF/classes/jdbc.properties"/>

<!-- 配置数据源   dbcp数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>



    
    
    
    


<!-- 配置mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 扫描包路径,如果需要扫描多个包中间用半角逗号隔开 -->
    <property name="basePackage" value="com.wxisme.ssm.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
Copy after login

  业务逻辑控制,applicationContext-service.xml的配置:

  这个文件里暂时只需要定义service的实现类即可。

<!-- 定义service -->
<bean id="userService" class="com.wxisme.ssm.service.impl.UserServiceImpl"/>
Copy after login

  事务控制,applicationContext-transaction.xml的配置

  配置数据源,使用JDBC控制类。

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 配置数据源 -->
    <property name="dataSource" ref="dataSource"/>
</bean>
Copy after login

  配置通知,事务控制。

<!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
Copy after login

  配置AOP切面

<!-- 配置aop  -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wxisme.ssm.service.impl.*.*(..))"/>
    </aop:config>
Copy after login

  整个事务控制的配置是这样的:



    


<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 配置数据源 -->
    <property name="dataSource" ref="dataSource"/>
</bean>
    
    
    
        
            
            
            
            
            
            
                        
        
    
    
    <!-- 配置aop  -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wxisme.ssm.service.impl.*.*(..))"/>
    </aop:config>
Copy after login

  MyBatis的配置                                                                                                                                             

  SqlMapConfig.xml的配置   全局setting配置这里省略,数据库连接池在spring整合文件中已经配置,具体setting配置参考官方文档。

  别名的定义:

<typeAliases>
    <!-- 批量定义别名 ,指定包名,自动扫描包中的类,别名即为类名,首字母大小写无所谓-->
    <package name="com.wxisme.ssm.po"/>
</typeAliases>
Copy after login

  mapper映射文件的配置:

<mappers>
    <!-- 加载映射文件 -->
    <!-- 这里也可以使用class来加载映射文件,前提是:使用mapper代理的方法,遵循规范,
    并且两个文件必须同名且在同一目录
    <mapper class="com.wxisme.mybatis0100.mapper.UserMapper"/>
    基于class加载,可以进行批量加载
    -->
    <!-- 通过扫描包的方式来进行批量加载映射文件 -->
    <package name="com.wxisme.ssm.mapper"/>     
</mappers>
Copy after login

  整个文件的配置应该是这样的:








<typeAliases>
    <!-- 批量定义别名 ,指定包名,自动扫描包中的类,别名即为类名,首字母大小写无所谓-->
    <package name="com.wxisme.ssm.po"/>
</typeAliases>




    
    

Copy after login

  具体mapper文件的配置,在使用mapper代理的方法时,命名空间需要是对应的Mapper类。

<?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.wxisme.ssm.mapper.AlbumMapper" >
  
</mapper>
Copy after login

  以上只是对SSM框架简单使用时的配置文件,如果需要深入使用或者需要理解其内部机理需要参考官方文档和其源代码。

The above is the detailed content of Detailed explanation of Spring, Spring MVC, MyBatis integration file configuration. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template