0%

7.ssm整合

7.ssm整合

7.1环境要求

环境:

  • IDEA
  • MySQL 5.7.19
  • Tomcat 9
  • Maven 3.6

要求:

  • 需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;

7.2创建books数据库

7.3基本环境搭建

  1. 新建maven项目

  2. 导入pom依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    <dependencies>
    <!--Junit-->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    </dependency>
    <!--数据库驱动-->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    </dependency>
    <!-- 数据库连接池 -->
    <dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
    </dependency>

    <!--Servlet - JSP -->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>

    <!--Mybatis-->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
    </dependency>

    <!--Spring-->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.9.RELEASE</version>
    </dependency>
    <!--lombok-->
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.10</version>
    </dependency>
    </dependencies>
  3. Maven资源过滤设置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <build>
    <resources>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    <resource>
    <directory>src/main/resources</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    </resources>
    </build>
  4. 建立基本的包结构和配置框架

    • com.lwj.pojo

    • com.lwj.dao

    • com.lwj.service

    • com.lwj.controller

    • mybatis-config.xml

      1
      2
      3
      4
      5
      6
      7
      <?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>

      </configuration>
    • applicationContext.xml(spring核心配置文件)

      1
      2
      3
      4
      5
      6
      7
      <?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
      http://www.springframework.org/schema/beans/spring-beans.xsd">

      </beans>

7.4Mybatis层编写

  1. 编写数据库配置文件

    1
    2
    3
    4
    5
    jdbc.driver=com.mysql.jdbc.Driver
    #如果使用的MySQL8.0以上版本,增加一个时区配置
    jdbc.url=jdbc:mysql://localhost:3306/mybatis_test
    jdbc.username=root
    jdbc.password=liwenjie
  2. 编写mybatis配置文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
        <!--日志-->
    <settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
    <package name="com.lwj.pojo"/>
    </typeAliases>
    <mappers>
    <mapper resource="mappers/BookMapper.xml"/>
    </mappers>
  3. idea关联数据库

  4. 编写数据库对应的实体类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
    }
  5. 编写dao层mapper接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public interface BookMapper {
    //增加一本书
    int addBook(Books book);
    //删除一本书
    int deleteBookById(int id);
    //更新一本书
    int updateBook(Books book);
    //查询一本书
    Books queryBookById(int id);
    //查询全部书
    List<Books> queryAllBook();

    }
  6. 编写mapper接口对应的mapper文件,放到resource/mappers/BookMapper.xml下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    <?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.lwj.dao.BookMapper">

    <!--增加一个Book-->
    <insert id="addBook" parameterType="Books">
    insert into books(bookName,bookCounts,detail)
    values (#{bookName}, #{bookCounts}, #{detail})
    </insert>

    <!--根据id删除一个Book-->
    <delete id="deleteBookById" parameterType="int">
    delete from books where bookID=#{bookID}
    </delete>

    <!--更新Book-->
    <update id="updateBook" parameterType="Books">
    update books
    set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
    where bookID = #{bookID}
    </update>

    <!--根据id查询,返回一个Book-->
    <select id="queryBookById" resultType="Books">
    select * from books
    where bookID = #{bookID}
    </select>

    <!--查询全部Book-->
    <select id="queryAllBook" resultType="Books">
    SELECT * from books
    </select>

    </mapper>
  7. 编写业务层Service的接口和实现类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.lwj.service;

    import com.lwj.pojo.Books;

    import java.util.List;

    public interface BookService {
    //增加一本书
    int addBook(Books book);
    //删除一本书
    int deleteBookById(int id);
    //更新一本书
    int updateBook(Books book);
    //查询一本书
    Books queryBookById(int id);
    //查询全部书
    List<Books> queryAllBook();
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    package com.lwj.service;

    import com.lwj.dao.BookMapper;
    import com.lwj.pojo.Books;

    import java.util.List;
    @Service
    public class BookServiceImpl implements BookService {
    //service 调dao层
    @Autowired
    private BookMapper bookMapper;

    //之后让spring来注入
    public void setBookMapper(BookMapper bookMapper) {
    this.bookMapper = bookMapper;
    }

    public int addBook(Books book) {
    return bookMapper.addBook(book);
    }

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

    public int updateBook(Books book) {
    return bookMapper.updateBook(book);
    }

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

    public List<Books> queryAllBook() {
    return bookMapper.queryAllBook();
    }
    }

    mybatis层到此为止,整合完毕

7.5spring层编写

  1. 配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;

  2. 我们去编写Spring整合Mybatis的相关的配置文件; spring-dao.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    <?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
    http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--关联数据库配置文件-->
    <context:property-placeholder location="database.properties"></context:property-placeholder>
    <!--连接池
    dbcp:半自动化操作,不能自动连接
    c3p0:自动化操作(自动化加载配置文件,并且自动设置到对象中)
    druid:
    hikari:
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"></property>
    <property name="jdbcUrl" value="${jdbc.url}"></property>
    <property name="user" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>

    <!-- c3p0连接池的私有属性 -->
    <property name="maxPoolSize" value="30"/>
    <property name="minPoolSize" value="10"/>
    <!-- 关闭连接后不自动commit -->
    <property name="autoCommitOnClose" value="false"/>
    <!-- 获取连接超时时间 -->
    <property name="checkoutTimeout" value="10000"/>
    <!-- 当获取连接失败重试次数 -->
    <property name="acquireRetryAttempts" value="2"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!--绑定mybatis的配置文件-->
    <property name="configLocation" value="mybatis-config.xml"></property>
    </bean>

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


    </beans>
  3. spring整合service

    新建spring-service.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <?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
    http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--扫描service下的包-->
    <context:component-scan base-package="com.lwj.service"></context:component-scan>

    <!--BookServiceImpl注入到IOC容器中-->
    <bean id="BookServiceImpl" class="com.lwj.service.BookServiceImpl">
    <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!--声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--aop横切事务-->


    </beans>

7.6springMVC层

  1. 添加web支持

  2. 配置web.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">



    <!--DispatcherServlet-->
    <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.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>

    <!--encodingFilter-->
    <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>
  3. 新建spring-mvc.xml

    配置springMVC

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <?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
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven />
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.lwj.controller" />

    </beans>
  4. Spring配置整合文件,applicationContext.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?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
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-service.xml"></import>
    <import resource="spring-dao.xml"></import>
    <import resource="spring-mvc.xml"></import>
    </beans>
  5. 在web-inf下建立jsp文件夹,配置结束

7.7配置tomcat

在第一个springMVC程序文章中已经详细介绍了,这里就不再累述。

添加tomcat;

配置tomcat项目;

配置artifacts,添加lib文件夹,导入全部包,否则404

7.8排错思路

  1. 查看bean是否注入成功
  2. Junit单元测试,看我们代码是否能查询结果
  3. 问题一定不在底层,是spring出问题
  4. springMVC整合的时候没有调用service层的bean
    • applicationContext.xml没有注入bean
    • web.xml中绑定配置文件

7.9查询全部书籍并显示

  1. 编写查询controller

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @Controller
    @RequestMapping("book")
    public class BookController {
    //Controller调service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部书籍并且返回到书籍展示页面
    @RequestMapping("allBook")
    public String list(Model model){
    List<Books> list =bookService.queryAllBook();
    model.addAttribute("list",list);
    return "allBook";
    }
    }
  2. 前台展示页面

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%--
    Created by IntelliJ IDEA.
    User: liwen
    Date: 2020/2/18
    Time: 11:14
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>书籍展示页面</title>
    </head>
    <body>
    <h1>书籍展示</h1>
    <div>
    <table>
    <thead>
    <tr>
    <td>书籍编号</td>
    <td>书籍名称</td>
    <td>书籍数量</td>
    <td>书籍详情</td>
    </tr>
    </thead>
    <tbody>
    <%--书籍从数据库中查询出来,从这个list中遍历出来--%>
    <c:forEach var="book" items="${list}">
    <tr>
    <td>${book.bookID}</td>
    <td>${book.bookName}</td>
    <td>${book.bookCounts}</td>
    <td>${book.detail}</td>
    </tr>
    </c:forEach>
    </tbody>
    </table>
    </div>
    </body>
    </html>

7.10添加书籍

  1. 新增书籍jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <%--
    Created by IntelliJ IDEA.
    User: liwen
    Date: 2020/2/18
    Time: 13:11
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>

    <form action="/book/addBook">
    书籍名称:<input type="text" name="bookName"><br>
    书籍数量:<input type="text" name="bookCounts"><br>
    书籍简介:<input type="text" name="detail"><br>
    <input type="submit">

    </form>

    </body>
    </html>
  2. Controller编写

    首先跳转到新增页面,提交接口到addBook,添加数据,然后重定向到http://localhost:8080/book/allBook

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //跳转到增加页面
    @RequestMapping("toAddBookPage")
    public String toAddBookPage(Model model){
    return "addBook";
    }
    @RequestMapping("addBook")
    public String addBook(Books books){
    bookService.addBook(books);
    return "redirect:allBook";
    }