美文网首页Ping说SSMssm
SpringMVC之整合SSM

SpringMVC之整合SSM

作者: Ping开源 | 来源:发表于2021-07-19 11:15 被阅读0次

    七、整合SSM

    目录:环境要求、基本环境搭建、代码编写

    1.环境要求

    • IDEA
    • MySQL 5.7.34
    • Tomcat 9.0.48
    • Maven 3.8.1

    数据库环境
    以书籍管理为例
    创建一个存放书籍数据的数据库表。
    测试表的创建及添加数据的代码,可下载使用:https://share.weiyun.com/QNwrCNrs,也可以直接复制下方。

    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` INT(11) 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,'SSM',8,'从光头到秃头'),
    (4,'Linux',5,'从进门到进牢');
    

    2.基本环境搭建

    1)新建一个Maven项目(ssmbuildaboutbooks),添加web app支持。
    2)导入相关的pom依赖。

    <dependencies>
      <!-- junit -->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
      </dependency>
      <!-- 数据库连接:mysql-connector-java -->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.49</version>
      </dependency>
      <!-- 数据库连接池:druid -->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.19</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.1-b03</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.7</version>
      </dependency>
      <!-- mybatis与spring整合 -->
      <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.3.9</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.9</version>
      </dependency>
      <!-- lombok -->
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
      </dependency>
    </dependencies>
    

    3)Maven资源过滤设置。

    <!-- 解决静态资源导出问题 -->
    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <excludes>
            <exclude>**/*.properties</exclude>
            <exclude>**/*.xml</exclude>
          </excludes>
          <filtering>false</filtering>
        </resource>
        <resource>
          <directory>src/main/java</directory>
          <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
          </includes>
          <filtering>false</filtering>
         </resource>
      </resources>
    </build>
    

    4)建立基本结构和配置框架。


    java文件夹下的基本结构

    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> 
    
    </configuration>
    

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

    3.代码编写

    1)MyBatis层编写
    ①数据库配置文件database.properties

    jdbc.driver=com.mysql.jdbc.Driver
    # 如果使用MySQL 8.0+,需要增加时区的配置 &serverTimezone=Asia/Shanghai
    jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false
    jdbc.username=root
    jdbc.password=123456
    

    ②IDEA关联MySQL数据库。
    ③编写MyBatis的核心配置文件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>
      <!-- 配置数据源,可以交给Spring去做 -->
    
      <typeAliases>
        <package name="com.ping.pojo"/>
      </typeAliases>
      <mappers>
        <mapper class="com.ping.dao.BookMapper"/>
      </mappers>
    </configuration>
    

    ④编写数据库对应的实体类Books.java
    使用了Lombok插件。

    package com.ping.pojo;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Books {
      private int bookID;
      private String bookName;
      private int bookCounts;
      private String detail;
    }
    

    ⑤ 编写Dao层的Mapper接口BookMapper.java

    package com.ping.dao;
    import com.ping.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    import java.util.List;
    public interface BookMapper {
      //增加一本Book
      int addBook(Books book);
      //根据id删除一本Book
      int deleteBookById(@Param("bookId") int id);
      //更新Book
      int updateBook(Books books);
      //根据id查询,返回一本Book
      Books queryBookById(@Param("bookId") int id);
      //查询全部的Book,返回一个List集合
      List<Books> queryAllBook();
    }
    

    ⑥编写接口对应的Mapper.xml文件,需要导入MyBatis的包BookMapper.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.ping.dao.BookMapper">
      <!-- 增加一本Book -->
      <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books(bookName, bookCounts, detail)
        value (#{bookName}, #{bookCounts}, #{detail})
      </insert>
      <!-- 根据id删除一本Book -->
      <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID = #{bookId}
      </delete>
      <!-- 更新Book -->
      <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
        where bookID = #{bookID}
      </update>
      <!-- 根据id查询,返回一本Book -->
      <select id="queryBookById" resultType="Books">
        select * from ssmbuild.books
        where bookID = #{bookId}
      </select>
    
        <!-- 查询全部的Book -->
        <select id="queryAllBook" resultType="Books">
            select * from ssmbuild.books
        </select>
    </mapper>
    

    ⑦编写Service层的接口和实现类。
    接口BookService.java

    package com.ping.service;
    import com.ping.pojo.Books;
    import java.util.List;
    public interface BookService {
      //增加一本Book
      int addBook(Books book);
      //根据id删除一本Book
      int deleteBookById(int id);
      //更新Book
      int updateBook(Books books);
      //根据id查询,返回一本Book
      Books queryBookById(int id);
      //查询全部的Book,返回一个List集合
      List<Books> queryAllBook();
    }
    

    实现类BookServiceImpl.java

    package com.ping.service;
    import com.ping.dao.BookMapper;
    import com.ping.pojo.Books;
    import org.springframework.beans.factory.annotation.Autowired;
    import java.util.List;
    public class BookServiceImpl implements BookService{
      //Service层调用Dao层操作,设置一个set接口,方便Spring管理
      @Autowired
      private BookMapper bookMapper;
      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 books) {
        return bookMapper.updateBook(books);
      }
      public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
      }
      public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
      }
    }
    

    2)Spring层编写
    ①配置Spring整合MyBatis,这里数据源使用alibaba的druid连接池。
    ②编写Spring整合Mybatis的相关的配置文件spring-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
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
      <!-- 配置整合MyBatis -->
      <!-- 关联数据库文件 -->
      <context:property-placeholder location="classpath:database.properties"/>
      <!-- 数据库连接池:druid -->
      <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}"/>
        <property name="validationQuery" value="SELECT 1 FROM DUAL" />
      </bean>
      <!-- 配置SqlSessionFactory对象 -->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 绑定MyBatis全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
      </bean>
      <!--配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.ping.dao"/>
      </bean>
    </beans>
    

    数据库连接池
    Ⅰdbcp:半自动化操作,不能自动连接。
    Ⅱc3p0:自动化操作(自动的加载配置文件,并且设置到对象里面)。
    Ⅲdruid
    ③Spring整合service层的配置文件spring-service.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:jdbc="http://www.springframework.org/schema/jdbc"
           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/jdbc
           http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
      <!-- 扫描service相关的bean -->
      <context:component-scan base-package="com.ping.service"/>
      <!-- BookServiceImpl注入到IoC容器中 -->
      <bean id="BookServiceImpl" class="com.ping.service.BookServiceImpl">
        <property name="BookMapper" ref="bookMapper"/>
      </bean>
      <!-- 配置事务管理器 -->
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
      </bean>
    </beans>
    

    3)SpringMVC层编写
    web.xml

    <?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">
      <!-- 配置springmvc的前端控制器,指向spring-mvc.xml程序在启动的时候就加载springmv 可以接受所有请求load-on-startup:表示启动容器时初始化该Servlet -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
      </context-param>
      <servlet>
        <servlet-name>springServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!-- 可以自定义servlet.xml配置文件的位置和名称, 默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath*:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <!-- 将前端URL请求和后台处理方法controller建立对应关系-->
      <servlet-mapping>
        <servlet-name>springServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
      <listener>
        <listener-class>
          org.springframework.web.context.ContextLoaderListener
        </listener-class>
      </listener>
      <!--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>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    

    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
           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 -->
      <!-- 开启SpringMVC注解驱动 -->
      <mvc:annotation-driven/>
      <!-- 静态资源默认servlet配置-->
      <mvc:default-servlet-handler/>
      <!-- 配置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>
      <!-- 扫描web相关的bean -->
      <context:component-scan base-package="com.ping.controller"/>
    </beans>
    

    ③Spring配置整合文件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
           http://www.springframework.org/schema/beans/spring-beans.xsd">
      <import resource="spring-dao.xml"/>
      <import resource="spring-service.xml"/>
      <import resource="spring-mvc.xml"/>
    </beans>
    

    4)Controller和视图层编写
    ①编写BookController类BookController.java

    package com.ping.controller;
    import com.ping.pojo.Books;
    import com.ping.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import java.util.List;
    @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";
      }
    }
    

    ②编写首页index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>首页</title>
      </head>
      <body>
        <h1>这是首页</h1>
        <h3>
          <a href="${pageContext.request.contextPath}/book/allBook">连接</a>
        </h3>
      </body>
    </html>
    

    ③编写获取书籍列表页面allbook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
      <head>
        <title>书籍列表</title>
      </head>
      <body>
        <h1>书籍展示</h1>
        <table width="600" border="1">
          <tr>
            <td>编号</td>
            <td>名称</td>
            <td>数量</td>
            <td>介绍</td>
          </tr>
          <c:forEach items="${list}" var="book">
            <tr>
              <td>${book.bookID}</td>
              <td>${book.bookName}</td>
              <td>${book.bookCounts}</td>
              <td>${book.detail}</td>
            </tr>
          </c:forEach>
        </table>
      </body>
    </html>
    

    还可以进行添加书籍、修改书籍、删除书籍等代码编写。
    配置Tomcat,进行测试。
    项目结构图

    SSM基础项目结构图

    SSM基础项目搭建(以书籍管理为例)的代码可下载使用:https://share.weiyun.com/8apKwEFh

    相关文章

      网友评论

        本文标题:SpringMVC之整合SSM

        本文链接:https://www.haomeiwen.com/subject/dzdypltx.html