ssm框架整合(简单图书管理)

SSM框架整合

学习视频,B站狂神说Java_springMVC

1、环境要求(笔者自己的环境)

环境:

  • IDEA 2019.03
  • MySQL 8.0.22
  • Tomcat 9
  • Maven 3.6

要求:熟练掌握MySQL 数据库,Spring,JavaWeb及Mybatis知识,简单的前端知识

如果前端知识拿不出手,可以直接利用工具生成前端代码:BootStrap可视化布局

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

3、基本环境搭建

  1. 新建一个普通的Maven项目,添加web支持(也可以直接创建一个Maven web项目工程)并配置Tomcat

  2. 导入相关的pom依赖

    <!--    导入依赖:
            junit, 数据库驱动, 连接池, servlet, jsp, mybatis, mybatis-spring, spring...
     -->
        <dependencies>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
            </dependency>
            <!--mysql 数据库驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.22</version>
            </dependency>
            <!--数据库连接池c3p0-->
            <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </dependency>
    
    
            <!--servlet-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
            <!--jsp-->
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
            </dependency>
            <!--jstl-->
            <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.2.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.0.RELEASE</version>
            </dependency>
    
    <!--        导入lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.10</version>
            </dependency>
    
        </dependencies>
    
  3. pom.xml添加静态资源过滤配置

        <!--    静态资源导出问题-->
        <!--在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>
    
        <!-- 解决配置文件中有中文而导致的错误-->
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    
  4. 建立项目的包结构

    ssm框架整合(简单图书管理)

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

4、Mybatis层整合

1、数据库配置文件db.properties

jdbc.driver=com.mysql.jdbc.Driver
# 如果使用的时mysql8.0+,需要增加一个时区的配置; &serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root

2、IDEA中打开指定的数据库

ssm框架整合(简单图书管理)

3、编写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资源配置-->
<configuration>

    <!--设置日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

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

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

</configuration>

4、编写数据库对应的实体类(pojo包)

偷懒的方式:需要导入lombok依赖,如果idea没有事先下载lombok插件的话还需要下载后重启idea

package com.liuxingwu.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author saodisheng
 * @Date 2021/3/5
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

5、编写Dao层的Mapper接口

package com.liuxingwu.dao;

import com.liuxingwu.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.awt.print.Book;
import java.util.List;

/**
 * @author saodisheng
 * @Date 2021/3/5
 */
public interface BookMapper {
    // 增加一本书
    int addBook(Books books);
    // 删除一本书
    int deleteBook(int id);
    // 更新一本书
    int updateBook(Books books);
    // 查询一本数据
    Books queryBookById(@Param("bookId") int id);
    // 查询全部书
    List<Books> queryAllBooks();
}

6、编写接口对应的Mapper.xml文件

当然也可以通过注解实现,这里使用的是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">

<!-- configuration资源配置-->
<mapper namespace="com.liuxingwu.dao.BookMapper">

<!--    增加一本书-->
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        values (#{bookName}, #{bookCounts}, #{detail})
    </insert>
<!--    删除一本书-->
    <delete id="deleteBook" >
        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>

7、业务层service层的接口及其实现类

接口

package com.liuxingwu.service;

import com.liuxingwu.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author saodisheng
 * @Date 2021/3/5
 */
public interface BookService {
    // 增加一本书
    int addBook(Books books);
    // 删除一本书
    int deleteBook(int id);
    // 更新一本书
    int updateBook(Books books);
    // 查询一本数据
    Books queryBookById(int id);
    // 查询全部书
    List<Books> queryAllBooks();
}

实现类

package com.liuxingwu.service;

import com.liuxingwu.dao.BookMapper;
import com.liuxingwu.pojo.Books;
import org.junit.Test;

import java.awt.print.Book;
import java.util.List;

/**
 * @author saodisheng
 * @Date 2021/3/5
 */
public class BookServiceImpl implements BookService {
    // Service层要调用dao层的方法,因此需要将组合一个dao层的实例
    private BookMapper bookMapper;


    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

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

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

    public int updateBook(Books books) {
        System.out.println(books);
        bookMapper.updateBook(books);
        return 1;
    }

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

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

5、Spring层整合

编写配置Spring配置文件,整合Mybatis

1、spring-dao.xml(整合dao层),这里使用的是c3p0连接池

<?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}"/>

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

    <!--    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.liuxingwu.dao"/>
    </bean>
</beans>

2、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.liuxingwu.service"/>
    
	<!--2.将所有的业务类注入到Spring,可以通过配置,或者注解-->
    <bean id="BookServiceImpl" class="com.liuxingwu.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>

6、SpringMVC层整合

1、SpringMVC配置文件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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:cnntext="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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--    1.注解驱动-->
    <mvc:annotation-driven/>
    
    <!--    2.打开静态资源过滤-->
    <mvc:default-servlet-handler/>
    
    <!--    3.扫描包:Controller 控制层-->
    <cnntext:component-scan base-package="com.liuxingwu.controller"/>
    
    <!--    4.视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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

    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>

3、配置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">
    
	<!--   DispatcherServlet SpringMVC控制中心 -->
    <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:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </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>

截止目前,基本的ssm框架已经整合完毕了。

ssm框架整合(简单图书管理)

7、Controller和视图层的编写

1、查询全部书籍

  1. 控制层:BookController

    package com.liuxingwu.controller;
    
    import com.liuxingwu.pojo.Books;
    import com.liuxingwu.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.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.List;
    
    /**
     * @author saodisheng
     * @Date 2021/3/5
     */
    @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.queryAllBooks();
            model.addAttribute("list", list);
            return "allBook";
        }
    }
    
  2. 编写首页index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>首页</title>
        <style>
          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: 5px; /*圆边框*/
          }
        </style>
      </head>
      <body>
      <h3>
        <a href="${pageContext.request.contextPath}/book/allbook">进入书籍页面</a>
      </h3>
      </body>
    </html>
    
  3. 书籍列表界面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>
        <%--    美化界面--%>
        <!-- 新 Bootstrap 核心 CSS 文件 -->
        <link href="https://cdn.staticfile.org/twitter-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">
                <h1>
                    <small>书籍列表————显示所有书籍</small>
                </h1>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 cloumn">
                <!--toAddBook-->
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allbook">显示所有书籍</a>
            </div>
    
            <div class="col-md-8 cloumn">
                <!--查询书籍-->
                <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float:right">
                    <span style="color: red">${error}</span>
                    <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍名称">
                    <input type="submit" value="查询" class="btn btn-primary">
                </form>
            </div>
        </div>
    
        <div class="row clearfix">
            <div class="col-md-12 cloumn">
                <table class="table table-hover table-striped">
                    <thead>
                    <tr>
                        <th>书籍编号</th>
                        <th>书籍名称</th>
                        <th>书籍数量</th>
                        <th>书籍详情</th>
                        <th>操作</th>
                    </tr>
                    </thead>
    <%--                书籍从数据库查询出来,从这个list中遍历出来:foreach--%>
                    <tbody>
                    <c:forEach var="book" items="${list}">
                        <tr>
                            <td>${book.bookID}</td>
                            <td>${book.bookName}</td>
                            <td>${book.bookCounts}</td>
                            <td>${book.detail}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/book/toUpdateBook?bookID=${book.bookID}">修改</a>
                                <%--添加空格--%>
                                &nbsp; | &nbsp;
                                <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    
    </div>
    <%--<h1>书籍展示</h1>--%>
    </body>
    </html>
    
    

2、添加数据

  1. BookController

    // 跳转到添加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPage() {
        return "addBook";
    }
    // 添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books) {
        System.out.println("addBook=>" + books);
        bookService.addBook(books);
        return "redirect:/book/allbook";        // 重定向到@RequestMapping("/allbook")
    }
    
  2. 添加书籍页面:addBook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>新增书籍</title>
        <%--    美化界面--%>
        <!-- 新 Bootstrap 核心 CSS 文件 -->
        <link href="https://cdn.staticfile.org/twitter-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">
                <h1>
                    <small>新增书籍</small>
                </h1>
            </div>
        </div>
        <form action="${pageContext.request.contextPath}/book/addBook" method="post">
            <div class="form-group">
                <label>书籍名称:</label>
                <input type="text" name="bookName" class="form-control" required>
            </div>
            <div class="form-group">
                <label>书籍数量:</label>
                <input type="text" name="bookCounts" class="form-control" required>
            </div>
            <div class="form-group">
                <label>书籍描述:</label>
                <input type="text" name="detail" class="form-control" required>
            </div>
            <div class="form-group">
                <input type="submit" class="form-control" value="添加">
            </div>
        </form>
    </div>
    </body>
    </html>
    

3、修改书籍

  1. BookController

     // 跳转到修改书籍页面
        // 接收前端传来的bookID,通过bookID查询指定的书籍
        @RequestMapping("/toUpdateBook")
        public String toUpdatePage(int bookID, Model model) {
            Books books = bookService.queryBookById(bookID);
            model.addAttribute("QBook", books);
            return "updateBook";
        }
        // 修改书籍的请求
        @RequestMapping("/updateBook")
        public String updateBook(Books books) {
            System.out.println("updateBook=>" + books);
            bookService.updateBook(books);
    //        System.out.println("修改成功");
            return "redirect:/book/allbook";        // 重定向到@RequestMapping("/allbook")
        }
    
  2. 修改页面:updateBook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>修改书籍</title>
        <%--    美化界面--%>
        <!-- 新 Bootstrap 核心 CSS 文件 -->
        <link href="https://cdn.staticfile.org/twitter-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">
                <h1>
                    <small>修改书籍</small>
                </h1>
            </div>
        </div>
        <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
            <%--出现的问题:提交了修改请求,但修改失败
                原因是修改需要主键,但之前没有传递相应的主键
            --%>
            <%--前端传递隐藏于,这点容易忽略,从而造成500错误--%>
            <input type="hidden" name="bookID" value="${QBook.bookID}">
            <div class="form-group">
                <label>书籍名称:</label>
                <input type="text" name="bookName" class="form-control" value="${QBook.bookName}" required>
            </div>
            <div class="form-group">
                <label>书籍数量:</label>
                <input type="text" name="bookCounts" class="form-control" value="${QBook.bookCounts}" required>
            </div>
            <div class="form-group">
                <label>书籍描述:</label>
                <input type="text" name="detail" class="form-control" value="${QBook.detail}" required>
            </div>
            <div class="form-group">
                <input type="submit" class="form-control" value="修改">
            </div>
        </form>
    </div>
    </body>
    </html>
    

4、删除书籍

  1. BookController

    // 删除书籍
    @RequestMapping("/deleteBook/{bookid}")
    public String deleteBook(@PathVariable("bookid") int bookID) {
        bookService.deleteBook(bookID);
        return "redirect:/book/allbook";        // 重定向到@RequestMapping("/allbook")
    }
    

8、体会一下在搭建好的ssm框架中添加新功能的步骤

添加一个图书查询的功能

1、dao接口BookMapper

之所以考虑返回一个列表是因为查询的实现采用的是模糊查询

// 通过书籍名称查询一本书名
List<Books> queryBook(String bookName);

2、BookMapper接口对应的配置文件BookMapper.xml

模糊查询

<!--通过书名查询书籍-->
<select id="queryBook" parameterType="string" resultType="Books">
    select * from ssmbuild.books where bookName like "%"#{bookName}"%"
</select>

3、业务层service接口BookService

// 通过书名查询书籍
List<Books> queryBook(String bookName);

4、业务层接口实现类

public List<Books> queryBook(String bookName) {
    return bookMapper.queryBook(bookName);
}

5、控制层BookController

// 查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName, Model model) {
    List<Books> booksList = bookService.queryBook(queryBookName);
    model.addAttribute("list", booksList);
    if (booksList.size() == 0) {
        model.addAttribute("error", "为找到相关书籍");
    }
    return "allBook";
}

6、视图层:allbook.jsp(在最开始时已经包含了,实际开发时应该是逐步完善功能的)

上一篇:罗马数字转整数--2021-11-08


下一篇:分布式之Redis【一】基础学习