SpringMVC-03-SSM整合

七、SSM整合

7.1 环境配置

  • IDE:IDEA

  • 数据库:MySQL 8.0.21

  • JDK14 + maven 3.6.3

  • maven依赖

    <dependencies>
        <!--JUnit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        
        <!--Spring框架-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>
        
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>provided</scope>
        </dependency>
        
        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.1</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>
        
        <!--Servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>
    </dependencies>
    
  • 设置maven静态资源过滤

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

7.2 数据库搭建

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,'Linux',5,'从进门到进牢');

7.3 系统架构设计

  • pojo:实体类包
  • mapper:MyBatis操作数据库接口,和pojo一起组成了Model
  • controller:Controller层
  • service:服务层

7.4 MyBatis

  • mysql配置文件

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT+8
    user=root
    pwd=123456
    
  • mybatis-config

    <typeAliases>
        <package name="com.pbx.pojo"/>
    </typeAliases>
    
    <mappers>
        <package name="com.pbx.mapper"/>
    </mappers>
    
  • spring整合MyBatis

    <!--扫描配置文件-->
    <context:property-placeholder location="classpath:mysql.properties"/>
    
    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${pwd}"/>
    </bean>
    
    <!--配置SQLSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="mybatis-config.xml"/>
    </bean>
    
    <!--自动扫描mapper接口,生成实体类,交由Spring管理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.pbx.mapper"/>
    </bean>
    
  • 实体类

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Book {
    
        private int bookID;
        private String bookName;
        private int bookCount;
        private String detail;
    
    }
    
  • mapper接口

    public interface BookMapper {
        // 增
        int addBook(Book book);
    
        // 删
        int deleteBookByID(@Param("bookid") int id);
    
        // 改
        int updateBook(Book book);
    
        // 查
        List<Book> selectAllBook();
        List<Book> selectBookByName(@Param("bookname") String name);
        Book selectBookByID(@Param("bookid") int id);
    }
    
  • mapper.xml

    <mapper namespace="com.pbx.mapper.BookMapper">
        <insert id="addBook" parameterType="book">
            insert into ssmbuild.books (bookName, bookCounts, detail) value (#{bookName}, #{bookCounts}, #{detail})
        </insert>
    
        <update id="updateBook" parameterType="book">
            update ssmbuild.books
            <set>
                <if test="bookName != null">bookName = #{bookName}</if>
                <if test="bookCounts != null">bookCounts = #{bookCounts}</if>
                <if test="detail != null">detail = #{detail}</if>
            </set>
            where bookID = #{bookID};
        </update>
    
        <delete id="deleteBookByID" parameterType="int">
            delete from ssmbuild.books where bookID = #{bookid};
        </delete>
    
        <select id="selectAllBook" resultType="book">
            select * from ssmbuild.books;
        </select>
        <select id="selectBookByName" resultType="book">
            select * from ssmbuild.books where bookName like '%'#{bookname}'%';
        </select>
        <select id="selectBookByID" resultType="com.pbx.pojo.Book">
            select * from ssmbuild.books where bookID = #{bookid};
        </select>
    </mapper>
    

7.5 Service层

  • service接口

    public interface BookService {
        // 增
        int addBook(Book book);
    
        // 删
        int deleteBookByID(int id);
    
        // 改
        int updateBook(Book book);
    
        // 查
        List<Book> selectAllBook();
        List<Book> selectBookByName(String name);
        Book selectBookByID(int id);
    }
    
  • service实现类

    public class BookServiceImpl implements BookService {
    
        private BookMapper mapper;
    
        public void setMapper(BookMapper mapper) {
            this.mapper = mapper;
        }
    
        @Override
        public int addBook(Book book) {
            return mapper.addBook(book);
        }
    
        @Override
        public int deleteBookByID(int id) {
            return mapper.deleteBookByID(id);
        }
    
        @Override
        public int updateBook(Book book) {
            return mapper.updateBook(book);
        }
    
        @Override
        public List<Book> selectAllBook() {
            return mapper.selectAllBook();
        }
    
        @Override
        public List<Book> selectBookByName(String name) {
            return mapper.selectBookByName(name);
        }
    
        @Override
        public Book selectBookByID(int id) {
            return mapper.selectBookByID(id);
        }
    }
    
  • spring整合service

    <!--给Service注入mapper-->
    <bean id="bookServiceImpl" class="com.pbx.service.BookServiceImpl">
        <property name="mapper" ref="bookMapper"/>
    </bean>
    
    <!--开启事务管理-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    

7.6 View层 + Controller层

  • 首页,index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8" %>
    <!DOCTYPE HTML>
    <html>
    
    <head>
      <title>首页</title>
      <style type="text/css">
        a {
          text-decoration: none;
          color: black;
          font-size: 18px;
        }
    
        h3 {
          width: 180px;
          height: 38px;
          margin: 100px auto;
          text-align: center;
          line-height: 38px;
          background: deepskyblue;
          border-radius: 4px;
        }
      </style>
    </head>
    
    <body>
      <h3>
        <a href="${pageContext.request.contextPath}/book/allBook">点击进入详情页</a>
      </h3>
    </body>
    
    </html>
    
  • allBook.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>书籍列表</title>
        <meta name="viewport" content="width=device-width, initialscale=
    1.0">
        <!-- 引入 Bootstrap -->
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 column">
                <div class="page-header"><h1>
                    <small>书籍列表 —— 显示所有书籍</small>
                </h1>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 column">
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAdd">新增</a>
            </div>
        </div>
        <div class="row clearfix">
            <div class="col-md-12 column">
                <table class="table table-hover table-striped">
                    <thead>
                    <tr>
                        <th>书籍编号</th>
                        <th>书籍名字</th>
                        <th>书籍数量</th>
                        <th>书籍详情</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <c:forEach var="book" items="${requestScope.get('list')}">
                        <tr>
                            <td>${book.getBookID()}</td>
                            <td>${book.getBookName()}</td>
                            <td>${book.getBookCounts()}</td>
                            <td>${book.getDetail()}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/book/toUpdate/${book.getBookID()}">更改</a> |
                                <a href="${pageContext.request.contextPath}/book/delete/${book.getBookID()}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
  • addBook.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>新增书籍</title>
        <meta name="viewport" content="width=device-width, initialscale=1.0">
        <!-- 引入 Bootstrap -->
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 column">
                <div class="page-header">
                    <h1>
                        <small>新增书籍</small>
                    </h1>
                </div>
            </div>
        </div>
        <form action="${pageContext.request.contextPath}/book/addBook" method="post">
            <div class="form-group">
                <label for="bookname">书籍名称</label>
                <input type="text" class="form-control" name="bookName" id="bookname" required>
            </div>
            <div class="form-group">
                <label for="bookcount">书籍数量</label>
                <input type="text" class="form-control" name="bookCounts" id="bookcount" required>
            </div>
            <div class="form-group">
                <label for="detail">书籍详情</label>
                <input type="text" class="form-control" name="detail" id="detail" required>
            </div>
            <div class="form-group">
                <input type="submit" class="form-control" value="提交">
            </div>
        </form>
    </div>
    
  • updateBook.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>新增书籍</title>
        <meta name="viewport" content="width=device-width, initialscale=1.0">
        <!-- 引入 Bootstrap -->
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 column">
                <div class="page-header">
                    <h1>
                        <small>修改书籍</small>
                    </h1>
                </div>
            </div>
        </div>
        <form action="${pageContext.request.contextPath}/book/updateBook/${oldBook.bookID}" method="post">
            <div class="form-group">
                <label for="bookname">新书籍名称</label>
                <input type="text" class="form-control" name="bookName" id="bookname" value="${oldBook.bookName}">
            </div>
            <div class="form-group">
                <label for="bookcount">书籍数量</label>
                <input type="text" class="form-control" name="bookCounts" id="bookcount" value="${oldBook.bookCounts}">
            </div>
            <div class="form-group">
                <label for="detail">书籍详情</label>
                <input type="text" class="form-control" name="detail" id="detail" value="${oldBook.detail}">
            </div>
            <div class="form-group">
                <input type="submit" class="form-control" value="提交">
            </div>
        </form>
    </div>
    
  • Controller

    @Controller
    @RequestMapping("/book")
    public class BookController {
    
        @Autowired
        @Qualifier("bookServiceImpl")
        private BookService service;
    
        @RequestMapping("/allBook")
        public String getAllBook(Model model) {
            model.addAttribute("list", service.selectAllBook());
            return "allBook";
        }
    
        @RequestMapping("/toAdd")
        public String toAddPaper() {
            return "addBook";
        }
    
        @RequestMapping("/addBook")
        public String addBook(Book book) {
            System.out.println(book);
            service.addBook(book);
            return "redirect:allBook";
        }
    
        @RequestMapping("/delete/{id}")
        public String deleteBook(@PathVariable String id) {
            service.deleteBookByID(Integer.parseInt(id));
            return "redirect:/book/allBook";
        }
    
        @RequestMapping("/toUpdate/{id}")
        public String toUpdate(@PathVariable int id, Model model) {
            model.addAttribute("oldBook", service.selectBookByID(id));
            return "updateBook";
        }
    
        @RequestMapping("/updateBook/{id}")
        public String updateBook(@PathVariable int id, Book book) {
            book.setBookID(id);
            service.updateBook(book);
            return "redirect:/book/allBook";
        }
    
    }
    
posted @ 2020-12-14 19:18  PrimaBruceXu  阅读(47)  评论(0编辑  收藏  举报