ssm基本框架的整合

2022-04-10 16:25:53 浏览数 (1)

一. 创建Maven工程,引入依赖,配置所需环境

依赖

  1. mybatis的依赖
  2. spring的依赖
  3. mybatis-spring整合所需的依赖
  4. spring mvc的依赖
代码语言:html复制
        <!--********** mybatis **********-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.3.0</version>
        </dependency>
代码语言:html复制
        <!--********** spring **********-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.9.1</version>
        </dependency>
代码语言:html复制
        <!--********** mybatis-spring **********-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
代码语言:html复制
        <!--********** spring mvc **********-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.1.0.M1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
代码语言:html复制
        <!--********** junit **********-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <!--********** mysql **********-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <!--********** druid **********-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <!--********** log **********-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.3.0-alpha14</version>
        </dependency>
代码语言:html复制
    <!--********** mybatis逆向工程 **********-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.1</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-maven-plugin</artifactId>
                        <version>1.4.1</version>
                    </dependency>
                    <dependency>
                        <groupId>com.alibaba</groupId>
                        <artifactId>druid</artifactId>
                        <version>1.2.8</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.28</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

webapp

  1. 向模块添加web框架支持
  2. 进入项目结构→模块→添加部署描述符→...srcmainwebappWEB-INFweb.xml
  3. 在webapp中添加存放静态资源的文件夹static,在WEB-INF中添加存放html页面的文件夹templates

tomcat

  1. 点击编辑配置
  2. 添加tomcat本地服务器
  3. 在部署中添加当前项目的的展开型包,将应用程序上下文修改为“/”
  4. 设置重新部署 更新类和资源

二. 程序结构的规定

  • src
    • main
      • java
        • com.ssm
          • controller
          • service
          • mapper
          • interceptor
          • pojo
      • resources
        • com.ssm.mapper
        • applicationContext-dao.xml
        • applicationContext-service.xml
        • spring-mvc-controller.xml
        • mybatis-config.xml
        • log4j.xml
        • generatorConfig.xml
        • jdbc.properties
      • webapp
        • static
        • WEB-INF
          • web.xml
          • templates
    • test
      • java

三. mybatis实现逆向工程

创建mybatis核心配置文件mybatis-config.xml

代码语言:html复制
<?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>
    <properties resource="**jdbc.properties**"/>

    <!-- pojo包的全地址 -->
    <typeAliases>
        <package name="**com.ssm.pojo**"/>
    </typeAliases>

    <!-- 设置连接数据库的环境 -->
    <environments default="development">
        <environment id="development">
            <!-- type="JDBC":使用原始的JDBC的方式管理事务 -->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 引入映射文件,mapper包的全地址 -->
    <mappers>
        <package name="**com.maximilian.mapper**"/>
    </mappers>
</configuration>

创建逆向工程的配置文件generatorConfig.xml

代码语言:html复制
<?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="DB2Tables" targetRuntime="**MyBatis3**">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/**数据库名**?useSSL=false&amp;useUnicode=ture&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai&amp;rewriteBatchedStatements=true"
                        userId="**用户名**"
                        password="**密码**">
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="**pojo包的全类名**"
                            targetProject="**java文件夹的绝对路径**">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="**mapper包的全类名**"
                         targetProject="**resources文件夹的绝对路径**">
            <property name="enableSubPackages" value="true"/>

        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator targetPackage="**mapper包的全类名**"
                             targetProject="**java文件夹的绝对路径**"
                             type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 逆向分析的表 -->
        <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
        <!-- domainObjectName属性指定生成出来的实体类的类名 -->
        <table tableName="表名" domainObjectName="**pojo类名**"/>
    </context>
</generatorConfiguration>

通过逆向工程创建mapper、pojo、mapper

  1. 点击maven
  2. 点击插件
  3. 找到mybatis-generator中的mybatis-generator:generate并点击

四. 整合MyBatis与Spring

准备工作

  1. 针对数据表创建对应的service接口与实现类
  2. service接口实现类上添加注解@Service 、@Transactional
  3. 通过注解@Resource向service实现类注入mapper(实现类)对象
  4. 在覆盖重写的方法中调用mapper方法

dao(mapper)的配置——applicationConfig-dao.xml

  • mapper包的扫描
代码语言:html复制
    <context:component-scan base-package="**com.ssm.mapper**"/>
  • 数据库连接池、数据库的连接
代码语言:html复制
    <context:property-placeholder location="classpath:**jdbc.properties**"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <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>
  • SqlSessionFactory的创建与生成mapper接口的代理对象
代码语言:html复制
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- pojo的别名映射扫描,在value后面填写pojo包的全类名 -->
        <property name="typeAliasesPackage" value="**pojo包的全类名**"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 扫描mapper接口,生成代理对象,生成的代理对象会储存在ioc容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="**mapper包的全类名**"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

service的配置——applicationConfig-service.xml

  • service包扫描
代码语言:html复制
<context:component-scan base-package="**com.ssm.service**"/>
  • 事务管理、事物注解驱动
代码语言:html复制
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

这两个xml文件的bean标签中需要:

代码语言:html复制
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"

五. 在test中测试service方法

  1. 创建测试类
  2. 在类上添加基于Spring的JUnit测试注解
代码语言:txt复制
@RunWith(SpringJUnit4ClassRunner.class)  

@ContextConfiguration(locations = {"classpath:/applicationContext-service.xml"})

  1. 添加测试属性,有接口的就一定要使用接口注入
  2. 测试方法

六. 整合Spring MVC

在spring-mvc-controller.xml配置

  • 扫描cotroller(如果有拦截器也要扫描拦截器的所在包)
代码语言:html复制
    <context:component-scan base-package="**com.ssm.controller**"/>
  • 配置thymeleaf视图解析器
代码语言:html复制
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <!-- 视图解析器的优先级 -->
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/**templates**/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
  • 开启mvc注解驱动
代码语言:html复制
    <mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 处理响应中文内容乱码 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
  • 设置视图跳转控制器(点击即跳转,中间不能有任何的逻辑)
代码语言:html复制
    <mvc:view-controller path="**请求体**" view-name="**页面名称**"/>
  • 开放对静态资源的访问
代码语言:html复制
    <mvc:default-servlet-handler/>
  • 可选:文件上传下载的文件解析器
代码语言:html复制
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
  • 可选:拦截器
代码语言:html复制
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 期待被拦截的请求 -->
            <mvc:mapping path="**/****"/>
            <!-- 不期待被拦截的请求 -->
            <mvc:exclude-mapping path="**/**"/>
            <ref bean="**拦截器类注解中的value**"/>
        </mvc:interceptor>
    </mvc:interceptors>

在web.xml中整合spring与spring mvc

  • 过滤器1:编码
代码语言:html复制
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • 过滤器2:隐藏的http请求方法
代码语言:html复制
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • 启动spring框架
代码语言:html复制
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:**applicationContext*.xml**</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  • 配置spring mvc的前端控制器dispatcher servlet,对浏览器发送的请求进行处理
代码语言:html复制
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:**spring-mvc-controller.xml**</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

0 人点赞