整体文件目录

1.maven

image-20220129150932260

pom.xml

    <packaging>war</packaging>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring.version>5.3.15</spring.version>
    </properties>
    <dependencies>
        
        <!-- SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>
                <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.14.RELEASE</version>
        </dependency>
        
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        
        <!--        Database-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.7.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <!--other-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.15</version>
        </dependency>
    </dependencies>

2. web.xml

image-20220129151002983

webapp/WEB_INNF/web.xml

      <!-- 配置DispatcherServlet -->
    <servlet>
        <servlet-name>SSM_demo</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置springMVC需要加载的配置文件
            spring-dao.xml,spring-service.xml,spring-web.xml
                   Mybatis - > spring -> springmvc
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-web.xml</param-value>
        </init-param>
        <!--        应该在 Web 应用程序启动时加载-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SSM_demo</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

3. dao层(mybatis持久层框架+druid连接池)

image-20220129190824037

3.1 spring-dao.xml

resources/sprig/spring-dao.xml

    <!-- #1.配置 db的资源-->
    <context:property-placeholder location="classpath:alidb.properties"/>
    <!-- #2.配置bean  datasource-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!--        连接池属性        -->
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.jdbcUrl}"/>
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <!--        druid连接池私有属性-->
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
        <!--                关闭连接后不自动commit -->
        <property name="defaultAutoCommit" value="false"/>
        <!--                获取连接超时时间 -->
        <property name="queryTimeout" value="10000"/>
    </bean>
    <!--#3.配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--        mybatis 的全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--                  扫描并使用pojo的别名-->
        <property name="typeAliasesPackage" value="com.yegetables.pojo"/>
        <!--                  扫描mapper需要的xml-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--#4.扫描mapper接口,动态实现接口,并注入ioc中    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--        注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--        给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.yegetables.dao"/>
    </bean>

3.2 mybatis-connfig.xml

resources/mybatis-config.xml

<?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>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true"/>

        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true"/>

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>

    </settings>
</configuration>

3.3 properties

在resources文件夹下存放db.properties的数据库连接资源文件

resources/db.properties

jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis
jdbc.username=mybatis
jdbc.password=*******
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.initialSize=10
jdbc.maxActive=10
jdbc.maxWait=2000

3.4 数据库表

create table books
(
    number   int auto_increment comment '书ID'
        primary key,
    name     varchar(100) not null comment '书名',
    language varchar(100) not null comment '语言'
);

3.5 pojo类

pojo层定义跟数据库表对应的pojo类

src/java/com/pojo/Books.java

package com.yegetables.pojo;
public class Books {
    public int number;
    public String name;
    public String language;
    //setter ,getter, 无参构造,有参构造
}

3.6 dao层接口

dao层的操作pojo接口

src/java/com/dao/BooksMapper.java

package com.yegetables.dao;
import com.yegetables.pojo.Books;
public interface BooksMapper {
    int insertBook(Books book);
    int deleteBookByNumber(int number);
    int updateBook(Books book);
    Books getBookByNumber(int number);
    List<Books> getBooks();
}

提示:为什么要给方法的参数添加@Param注解呢?是因为该方法有两个或以上的参数,一定要加,不然mybatis识别不了。方法只有一个参数book_id,所以可以不用加 @Param注解,当然加了也无所谓~

​ int insertAppointment(@Param("bookId") long bookId, @Param("studentId") long studentId);

3.7 编写sql

编写dao层mapper接口对应的sql语句

resources/mapper/BooksMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yegetables.dao.BooksMapper">
    <insert id="insertBook" parameterType="Books">
        insert
        into books (number, name, language)
        values (#{number}, #{name}, #{language});
    </insert>
    <delete id="deleteBookByNumber" parameterType="int">
        delete
        from books
        where number = #{number};
    </delete>
    <update id="updateBook" parameterType="Books">
        update books
        set name=#{name},
            language=#{language}
        where number = #{number};
    </update>
    <select id="getBookByNumber" parameterType="int" resultType="Books">
        select number, name, language
        from books
        where number = #{number};
    </select>
    <select id="getBooks" resultType="Books">
        select number, name, language
        from books;
    </select>
</mapper>

4. services 层

4.1 spring-services.xml

resources/spring/sprinng-services.xml

    <!--    扫描注解@Service-->
    <context:component-scan base-package="com.yegetables.service"/>
    <!--    配置事务管理器,把事务管理交由spring来完成-->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--   默认启用:配置基于注解的声明式事务,可以直接在方法上@Transaction-->
    <!--    <tx:annotation-driven transaction-manager="transactionManager" />-->

4.2 src/services

image-20220129160329970

分两个目录

一个是service目录下的业务接口

一个是services.impl 目录下的接口实现类

5. web层

resources/spring/spring-web.xml

    <!-- 1.扫描web层 @Controller-->
    <context:component-scan base-package="com.yegetables.controller"/>

    <!-- 2.开启SpringMVC注解模式
            (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
            (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
    -->
    <mvc:annotation-driven/>

    <!-- 3.静态资源默认servlet配置
            (1)加入对静态资源的处理:js,gif,png
            (2)允许使用"/"做整体映射
    -->
    <mvc:default-servlet-handler/>

    <!-- 4.jsp视图解析器  : 可以更换成 模板  thymeleaf 等  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
        <!--        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />-->
    </bean>

Junit5

package com.yegetables.service;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = {"classpath:spring/spring-dao.xml", "classpath:spring/spring-web.xml", "classpath:spring/spring-service.xml"})
public class BookTest {
    @Autowired
    private BooksMapper bookMapper;
    @Test
    public void test(){
        
    }
}

junit4

@RunWith(SpringJUnit4ClassRunner.class)
//引入Spring配置
@ContextConfiguration({"classpath:spring/spring-dao.xml", "classpath:spring/spring-web.xml", "classpath:spring/spring-service.xml"})

themleaf

spring-web.xml

 <!--    配置thymeleaf模板解析器-->
    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver" id="templateResolver">
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".html"/>
        <property name="characterEncoding" value="utf-8"/>
<!--        是否设置缓存-->
        <property name="cacheable" value="false"/>
<!--        模板的类型 -->
        <property name="templateMode" value="HTML5"/>
     </bean>
<!--模板引擎-->
    <bean id="engine" class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
    </bean>
<!--    视图解析器-->
    <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver" id="resolver">
        <property name="templateEngine" ref="engine"/>
    </bean>

删除

    <!-- 4.jsp 视图解析器  : 可以更换成 模板  thymeleaf 等  -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            <property name="prefix" value=""/>
            <property name="suffix" value=".html"/>
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        </bean>

test.html添加名命名空间xmlns:th="http://www.thymeleaf.org"

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

资料来源

特别感谢 手把手教你整合最优雅SSM框架:SpringMVC + Spring + MyBatis

mybatis官方文档

【狂神说Java】SpringMVC最新教程IDEA版通俗易懂

尚硅谷Spring框架视频教程(spring5源码级讲解)