SSM框架

1. 数据库创建

create database ssmbuild;

use ssmbuild;

drop table if exists books;

create table books(

bookID int(10) not null auto_increment comment '书id',
bookName varchar(100) not null comment '书名',
bookCounts varchar(100) not null comment '数量',
detail varchar(200) not null comment '描述',
key bookID(bookID)
)engine = innodb default charset=utf8;


insert into books(bookID,bookName,bookCounts,detail) values
(1,'Java',1,'入门到放弃'),
(2,'MySQL',10,'删库到跑路'),
(3,'Linux',5,'进门到进牢');

2. 导入相关的pom文件

    <!-- 依赖: junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring -->
    <dependencies>

        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>

        <!-- Servlet -->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.11.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.11.RELEASE</version>
        </dependency>

    </dependencies>

静态资源导出问题

<!-- 在build中配置resources,来防止我们资源导出失败的问题 -->
<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>

        </resources>
</build>

3. 准备工作

1. 包结构创建

图片说明

2. 相关配置文件

  • applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>
  • mybatis-config.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <!-- 起别名 -->
    <typeAliases>
        <package name="com.Rickduck.pojo" />
    </typeAliases>

    <mappers>
        <mapper class="com.Rickduck.dao.BookMapper" />
    </mappers>

</configuration>
  • db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=888888

3. 编写相关类文件

  • dao层

    • Mapper类
    package com.Rickduck.dao;
    import com.Rickduck.pojo.Books;
    
    import java.util.List;
    
    public interface BookMapper {
    
        //增加
        int addBook(Books books);
        //删除
        int deleteBookById(int id);
        //更新
        int updateBook(Books books);
        //查询
        Books queryBookByI(int id);
        //查询全部
        List<Books> queryAllBooks();
    }
    
    • 对于的Mapper.xml
    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.Rickduck.dao.BookMapper">
    
        <insert id="addBook" parameterType="Books">
            insert into ssmbuild.books(bookName,bookCounts,detail)
            values(#{bookName},#{bookCounts},#{detail});
        </insert>
    
        <delete id="deleteBookById" parameterType="int">
            delete from ssmbuild.books where bookID = #{bookId}
        </delete>
    
        <update id="updateBook" parameterType="Books">
            update ssmbuild.books set
            bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
            where bookID=#{bookID}
        </update>
    
        <select id="queryBookById" resultType="Books">
            select * from ssmbuild.books where bookID = #{bookID}
        </select>
    
        <select id="queryAllBooks" resultType="Books">
            select * from ssmbuild.books
        </select>
    
    </mapper>
    • 记得在mybatis-config.xml中配置Mapper.xml
        <mappers>
            <mapper class="com.Rickduck.dao.BookMapper" />
        </mappers>
  • service层

    • 创建相应Servlet接口
    package com.Rickduck.service;
    
    import com.Rickduck.pojo.Books;
    
    import java.util.List;
    
    public interface BookService {
    
        //增加
        int addBook(Books books);
        //删除
        int deleteBookById(int id);
        //更新
        int updateBook(Books books);
        //查询
        Books queryBookById(int id);
        //查询全部
        List<Books> queryAllBooks();
    
    }
    • 实现Service接口方法(业务)
    package com.Rickduck.service;
    
    import com.Rickduck.dao.BookMapper;
    import com.Rickduck.pojo.Books;
    
    import java.util.List;
    
    public class BookServiceImpl implements BookService{
    
        //service层调dao层
        private BookMapper bookMapper;
    
        public void setBookMapper(BookMapper bookMapper) {
            this.bookMapper = bookMapper;
        }
    
        public BookMapper getBookMapper(){
            return bookMapper;
        }
    
    
  @Override
  public int addBook(Books books) {
      return bookMapper.addBook(books);
  }

  @Override
  public int deleteBookById(int id) {
      return bookMapper.deleteBookById(id);
  }

  @Override
  public int updateBook(Books books) {
      return bookMapper.updateBook(books);
  }

  @Override
  public Books queryBookById(int id) {
      return bookMapper.queryBookById(id);
  }

  @Override
  public List<Books> queryAllBooks() {
      return bookMapper.queryAllBooks();
  }

}

- Spring层

  - 增加`spring-dao.xml`,添加关联dao层的配置

  ``` 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:context="http://www.springframework.org/schema/context"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
          https://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          https://www.springframework.org/schema/context/spring-context.xsd">

      <!-- 1.关联数据库配置文件 -->
      <context:property-placeholder location="classpath*:db.properties" />

      <!-- 2.连接池 -->
      <!--
          dbcp: 半自动化操作,不能自动连接
          c3p0: 自动化操作(自动化的加载配置文件,并且可以设置到对象中)
          druid
          hikari
      -->
      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="${jdbc.driver}" />
          <property name="jdbcUrl" value="${jdbc.url}" />
          <property name="user" value="${jdbc.username}" />
          <property name="password" value="${jdbc.password}" />
      </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" />
      </bean>

      <!-- 配置dao扫描包,动态实现Dao接口注入到Spring容器中 -->
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <!-- 注入 sqlSessionFactory -->
          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
          <!-- 扫描的dao包 -->
          <property name="basePackage" value="com.Rickduck.dao" />
      </bean>

  </beans>

图片说明

  • 增加spring-service.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"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
          https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
      <!-- 1.扫描service下的包  -->
      <context:component-scan base-package="com.Rickduck.service" />
    
      <!-- 2.将业务类注入到Spring [配置]或[注解] -->
    <!--    <bean id="BookServiceImpl" class="com.Rickduck.service.BookServiceImpl">-->
    <!--        <property name="bookMapper" ref="bookMapper" />-->
    <!--    </bean>-->
    
      <!-- 3.声明书事务配置 -->
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <!-- 注入数据源 -->
          <property name="dataSource" ref="dataSource" />
      </bean>
    
      <!-- 4.aop事务支持 -->
    
    </beans>
  • 注解实现注入:

图片说明

  • 增加spring-mvc.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:context="http://www.springframework.org/schema/context"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
          https://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          https://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/mvc
          https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
      <!-- 1.注解驱动 -->
      <mvc:annotation-driven />
    
      <!-- 2.静态资源过滤 -->
      <mvc:default-servlet-handler />
    
      <!-- 3.扫描包: controller -->
      <context:component-scan base-package="com.Rickduck.controller" />
    
      <!-- 4.视图解析器 -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix" value="/WEB-INF/jsp/" />
          <property name="suffix" value=".jsp" />
      </bean>
    
    </beans>

Spring整合SpringMVC

  • 增加Web项目支持

1610028219320

  • 配置web.xml
    • DispatchServlet前端控制器
    • CharacterEncodingFilter 乱码过滤
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">

    <!-- DispatchServlet -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 乱码过滤 -->
    <filter>
        <filter-name>encodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Session -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

</web-app>