SSM整合配置(Spring+Spring MVC+Mybatis)

一、配置准备

   通过Maven工程,在eclipse中整合SSM,并在Tomcat服务器上运行  

  在进行配置前,先理清楚要配置哪些文件,如图,除web.xml外,其余三个配置文件名称均可自定义:

SSM整合配置(Spring+Spring MVC+Mybatis)_第1张图片

   如图所示,一共有四个需要手动配置的文件:

  1、web.xml:配置servlet、filter、listener

  2、applicationContext.xml:配置相关的bean,与mybatis整合

  3、Spring-Servlet.xml:用于配置视图解析器、控制器等

  4、GenratorConfig.xml:用于生成Mybatis用到的实体类、Mapper接口、Map配置文件 

  新建一个Maven工程,工程结构如图:

SSM整合配置(Spring+Spring MVC+Mybatis)_第2张图片

 

二、配置过程

  大致了解所需配置文件后,开始配置

  1、Web.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.0modelVersion>
  <groupId>ssmgroupId>
  <artifactId>ssmartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>ssm Maven Webappname>
  <url>http://maven.apache.orgurl>
  <properties>    
    <spring.version>5.0.0.RELEASEspring.version>
    
    <mybatis.version>3.4.5mybatis.version>
    
    <slf4j.version>1.7.25slf4j.version>
    <log4j.version>1.2.17log4j.version>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-oxmartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
      <scope>testscope>
    dependency>
    
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>com.github.pagehelpergroupId>
      <artifactId>pagehelperartifactId>
      <version>4.1.6version>
    dependency>
    <dependency>
      <groupId>tk.mybatisgroupId>
      <artifactId>mapperartifactId>
      <version>3.3.8version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>
    
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      
      <version>8.0.13version>
    dependency>
    
    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.4version>
    dependency>
    
    
  dependencies>
  <build>
    <finalName>ssmfinalName>
    <plugins>
         <plugin>
          <groupId>org.mybatis.generatorgroupId>
          <artifactId>mybatis-generator-maven-pluginartifactId>
          <version>1.3.2version>
          
          <configuration>
            <configurationFile>
              src/main/resources/generatorConfig.xml
            configurationFile>
            <verbose>trueverbose>
            <overwrite>trueoverwrite>
          configuration>
          
          <dependencies>
            <dependency>
              <groupId>org.mybatis.generatorgroupId>
              <artifactId>mybatis-generator-coreartifactId>
              <version>1.3.2version>
            dependency>
            <dependency>
              <groupId>mysqlgroupId>
              <artifactId>mysql-connector-javaartifactId>
              
              <version>8.0.13version>
            dependency>
          dependencies>
        plugin>
    plugins>
  build>
project>

   spring mvc采用前置控制器的设计模式,由一个DispatcherServlet负责分派,因此要在web.xml中对这个Servlet进行配置,该Servlet在启动时便实例化,因此要配置load-on-startup属性,我们先了解一下Spring MVC中的Context Hierarchy,首先看一张来自官网的图

SSM整合配置(Spring+Spring MVC+Mybatis)_第3张图片

  WebApplicationContext是ApplicationContext的拓展,是用于生成Bean的工厂,每个DispatcherServlet都需要一个Servlet WebApplicationContext来进行自己的配置,多个DispatcherServlet共享一个Root WebApplicationContext的配置,通常,在Servlet WebApplicationContext中配置控制器、视图解析器,在Root WebApplicationContext配置需要被多个Servlet共享的业务逻辑以及数据访问的Bean。

  每个DispatcherServlet对应的Servlet WebApplicationContext,默认名称为[servlet-name]-servlet,如本例中web.xml中配置servlet-name为spring,那么默认的Servlet WebApplicationContext配置文件名称便为spring-servlet,其默认路径在WEB-INF下,当然,也可以通过在Servlet中配置init-param的contextConfigLocation来自定义配置路径以及配置名称,本例中不进行配置,采用默认的名称 spring-servlet

SSM整合配置(Spring+Spring MVC+Mybatis)_第4张图片  

   对于Root WebApplicationContext的配置,首先要在web.xml中通过标签,设置该标签中contextConfigLocation的值,指定Root WebApplicationContext的路径与名称,随后在通过配置一个名为org.springframework.web.context.ContextLoaderListener的监听器,在启动时读取contextConfigLocation指定的Root WebApplicationContext,这里指定的Root WebApplicationContext在src/main/resources/applicationContext.xml中。配置完毕后的web.xml如下所示

DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app> 
  <context-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:applicationContext.xmlparam-value>
  context-param>
    
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
   <servlet>
      <servlet-name>springservlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      servlet-class>
      <load-on-startup>1load-on-startup>
   servlet>
   <servlet-mapping>
      <servlet-name>springservlet-name>
      <url-pattern>/url-pattern>
   servlet-mapping>  
web-app>

2、spring-servlet.xml配置

  在该配置文件中,主要配置控制器与视图解析器,配置过程比较简单,先在工程中新建一个实现控制器的包,这里定义为ssm.controller,随后配置一个视图解析器的bean以及扫描控制器注解,配置完毕后如图所示

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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <context:annotation-config/>       
    
    <context:component-scan base-package="ssm.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>
beans>

3、generatorConfig.xml配置

  要在applicationContext.xml中整合spring与mybatis,至少要配置两样东西:一个 SqlSessionFactory 和至少一个数据映射器类,因此,我们要先通过generatorConfig.xml,帮助我们自动生成实体对象、Mapper接口,以及对应的Mapper.xml文件。generatorConfig.xml的路径由pom.xml中configurationFile指定

SSM整合配置(Spring+Spring MVC+Mybatis)_第5张图片

 

 

  在这个配置文件中:

  jdbcConnection指定数据连接

  javaModelGenerator指定要生成的实体对象的位置,

  sqlMapGenerator指定要生成的Map.xml文件的位置

  javaClientGenerator指定要生成的Mapper接口的位置

  table指定要生成的表,通过enable**ByExample属性,指定是否要生成example文件

  我们指定生成的数据表如下:

  SSM整合配置(Spring+Spring MVC+Mybatis)_第6张图片

  最终配置文件如图

xml version="1.0" encoding="UTF-8"?>
DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
        
<generatorConfiguration>
    
    
    <context id="test" defaultModelType="flat">
    
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            
            <property name="suppressAllComments" value="true"/>
        commentGenerator>
    
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&utoReconnectForPools=true&
                        useUnicode=true&characterEncoding=utf-8&useSSL=false&
                        serverTimezone=UTC"
                        userId="root" password="wqk123">
        jdbcConnection>
        
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>
        
        <javaModelGenerator targetPackage="com.entity" targetProject="src/main/java">
        javaModelGenerator>
        
        <sqlMapGenerator targetPackage="map" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>
        
        <javaClientGenerator targetPackage="com.map" type="XMLMAPPER" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>
        
        <table tableName="food_item" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
    enableSelectByExample="false" selectByExampleQueryId="false">            
            <generatedKey column="food_id" sqlStatement="MySql" identity="true"/>
        table>
    
    context>
    
    
generatorConfiguration>

  配置完毕后,在项目上指定maven build,并设置Goalsmybatis-generator:generate -X,随后自动生成相应文件如图

SSM整合配置(Spring+Spring MVC+Mybatis)_第7张图片

 

4、配置applicationContext.xml

  在配置generatorConfig.xml时提到了,如果要想在applicationContext.xml中实现Mybatis与spring的整合,那么至少需要配置两样东西:一个 SqlSessionFactory至少一个数据映射器类,此外,在applicationContext.xml中还要扫描实现业务逻辑的service包并配置数据库链接源  

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"
       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/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&utoReconnectForPools=true&
                        useUnicode=true&characterEncoding=utf-8&useSSL=false&
                        serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="wqk123"/>
    bean>
    
    
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="typeAliasesPackage" value="com.entity"/>
        
        
        <property name="mapperLocations" value="classpath:map/FoodItemMapper.xml"/>
        
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="com.map"/>
        
        <property name="sqlSessionFactoryBeanName" >
            <idref bean="SqlSessionFactory"/>
        property>
    bean>
    
    <context:component-scan base-package="com.service"/>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
beans>

至此,配置以及完成

三、验证配置

  实现一个简单的功能,通过id参数读取相应食品的名称以及描述

1、定义业务逻辑的service接口并实现

SSM整合配置(Spring+Spring MVC+Mybatis)_第8张图片

2、定义控制器并实现

SSM整合配置(Spring+Spring MVC+Mybatis)_第9张图片

3、测试实际效果

 

 

 

 

 

转载于:https://www.cnblogs.com/wangqinkuan/p/10089643.html

你可能感兴趣的:(SSM整合配置(Spring+Spring MVC+Mybatis))