SSM整合

 

SSM框架整合

环境

  • IDEA
  • MySQL 5.5
  • Tomcat 8.5.34
  • Maven 3.6.0

搭建数据库(MySQL)

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

基本项目的搭建

  1. 新建maven项目,添加web支持

  2. 导入相关的maven依赖

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

    3.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>
    
    1. 建立基本结构和配置框架

      • com.inspur.pojo (持久层)

      • com.inspur.dao (Dao层)

      • com.inspur.service (业务处理层)

      • com.inspur.controller (业务控制层)

      • mybatis-config.xml (可在IDEA中设置xml模版) --> File | Settings | 编辑器 | 文件和代码模板

        <?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>
            
            <!-- 别名设置 pojo:实体类上可加注解 @Alias("books")-->
            <!--可在Mapper.xml文件中使用时无需类的全限定名,默认为类名 -->
            <typeAliases>
                <package name=""/>
            </typeAliases>
            <!-- mapper文件路径 -->
            <mappers>
                <mapper resource=""></mapper>
            </mappers>
        </configuration>
        
      • applicationContext.xml (IDEA含有spring的初始化的配置文件)

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

Mybatis层

  1. 数据库配置文件db.properties (设为模版,同上), --> 在Spring配置文件中读取

    jdbc.driver=com.mysql.jdbc.Driver
    #如果使用MySQL8.0+,需要增加一个时区的配置; &serverTimezone=Asia/Shanghai
    jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=123456
    
  2. IDEA关联数据库(idea自带的数据库链接)

  3. 编写(完善配置信息 注意标签的顺序)MyBatis的核心配置文件(mybatis-config.xml)

        <!-- 标准的 日志工厂实现  -->
        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
            <!--  是否开启自动驼峰命名规则 (camel case)映射 -->
            <!--  <setting name="mapUnderscoreToCamelCase" value="true"/>-->
    		<!-- 开启全局缓存  -->
            <setting name="cacheEnabled" value="true"/>
        </settings>
    
    
    <typeAliases>
    	<package name="com.inspur.pojo"/>
    </typeAliases>
    <mappers>
    	<mapper resource="com.inspur.dao.BookNapper.xml"/>
    </mappers>
    
  4. 编写数据库对应的实体类com.inspur.pojo.Books

    使用Lombok插件
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.apache.ibatis.type.Alias;
    import java.io.Serializable;
    /**
     * @author 12093
     * @Created by 12093
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Alias("books")   //可在Mapper.xml文件中使用,无需类的全限定名
    public class Books implements Serializable {
         //我们需要将实体类序列化(implements Serializable)!否则就会报错!
         private int bookID;
         private String bookName;
         private int bookCounts;
         private String detail;
    }
    
  5. 编写Dao层的Mapper接口

    import com.inspur.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    import java.util.List;
    /**
     * @author 12093
     */
    public interface BookMapper {
        //实现 增/删/改/查
        // 增加一本书
        int addBook(Books books);
        //  删除一本书
        int deleteBookById(@Param("bookID") int id);
        // 更新一本书
        int updateBookById(Books books);
    	// 查询一本书
        Books queryBookById(@Param("bookID") int id);
        // 查询全部的书
        List<Books> queryAllBook();
        //根据ID查询一本书
        List queryBookByName(@Param("bookName") String bookName);
        
    }
    
  6. 编写接口对应的Mapper.xml文件(最好与其接口 同名/同路径)

    <?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">
    <!--   MyBatis映射文件  -->
    <!--namespace=绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.inspur.dao.BookMapper">
        <cache/>   <!-- 设置此xml文件,使用二级缓存  -->
        
        <!--增加一个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="updateBookById" 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>
        
        <!--根据bookName查询,返回一个Book-->
        <select id="queryBookByName" resultType="Books">
            select * from books where bookName like "%"#{bookName}"%"
        </select>
        
    </mapper>
    
  7. 编写Service层的接口和实现类

    接口:

    package com.inspur.service;
    
    import com.inspur.pojo.Books;
    import java.util.List;
    /**
     * @author 12093
     * @Classname BookService
     * @Date 2020/11/8 22:58
     *   BookService:底下需要去实现,调用dao层
     */
    public interface BookService {
        // 增加一本Book
        int addBook(Books books);
        
        //根据id删除一本书Book
        int deleteBookById(int id);
    
        // 更新Book
        int updateBookById(Books books);
    
        //根据ID查询,返回一个Book
        Books queryBookById(int id);
    
        //查询全部Book,返回list集合
        List<Books> queryAllBook();
        
        //根据书名模糊查询一本书
     List<Books> queryBookByName(@Param("bookName") String bookName);
    }
    
   
   实现类:
   
   ```java
   mport com.inspur.dao.BookMapper;
   import com.inspur.pojo.Books;
   import java.util.List;
   public class BookServiceImpl implements BookService{
      
       //service调dao层:  组合Dao    可添加业务
       private BookMapper bookMapper;
   
       public void setBookMapper(BookMapper bookMapper) {
           this.bookMapper = bookMapper;
       }
   
       @Override
       public int addBook(Books books) {
           return bookMapper.addBook(books);
       }
   
       @Override
       public int deleteBookById(int id) {
           return bookMapper.deleteBookById(id);
       }
   
       @Override
       public int updateBookById(Books books) {
           return bookMapper.updateBookById(books);
       }
   
       @Override
       public Books queryBookById(int id) {
           return bookMapper.queryBookById(id);
       }
   
       @Override
       public List<Books> queryAllBook() {
           return bookMapper.queryAllBook();
    }
       
     @Override
       public List<Books> queryBookByName(String bookName) {
           return bookMapper.queryBookByName(bookName);
       }
   }

底层需求操作完毕

Spring层

🕶️注意事项: 所有的Spring的配置文件,配置的应用程序上下文在一个文件中

 
  1. 配置 Spring整合MyBatis ,这里使用c3p0连接池;
  2. 我们去编写Spring整合MyBatis的相关配置文件; Spring-dao.xml (多个Spring配置文件,整合,分层管理)
    <?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">
        
    <!--    DataSource:使用Spring的数据源替换MyBatis的配置 c3p0/dbcp/druid-->
    <!--    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的全局配置文件:mybatis-config.xml -->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
    <!-- 4. 配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中! -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--        注入sqlSessionFactory-->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!--        给出需要扫描的Dao接口包  -->
            <property name="basePackage" value="com.inspur.dao"/>
        </bean>
    </beans>
    
  3. Spring整合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 http://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.inspur.service"/>
    
    <!--   2. 将我们的所有业务类,注入到springIOC容器中,可以通过配置,或者注解实现-->
        <!-- BookServiceImpl 注入到 IOC容器中  -->
        <bean id="BookServiceImpl" class="com.inspur.service.BookServiceImpl">
            <property name="bookMapper" ref="bookMapper"/>
        </bean>
    
    <!--   3. 配置事务管理器 -->
        <bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入数据源 -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
    </beans>
    

    Spring层搞定! Spring就是一个大杂烩,一个容器!

SpringMVC层

  1. 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">
    <!--    DispatchServlet  -->
        <servlet>
            <servlet-name>DispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
            <!-- 一定要注意: 这里加载的是总的配置文件!!!  不是Spring-mvc.xml   -->
                <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>
            <!--  "/",处理所有文件; "/*"不处理.jsp文件    -->
        </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>
    
  2. 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:nvc="http://www.springframework.org/schema/mvc" xmlns:mvc="http://www.springframework.org/schema/mvc"
           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/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--  配置SpringMVC  -->
        <!--    1.开启SpringMVC注解驱动 -->
        <nvc:annotation-driven/>
        
        <!--    2.静态资源过滤默认servlet配置 -->
        <mvc:default-servlet-handler/>
        
        <!--    3.扫描web相关的bean:controller -->
        <context:component-scan base-package="com.inspur.controller"/>
        
        <!--    4.配置jsp显示ViewResolver试图解析器  -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>
    
  3. 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="classpath:spring-dao.xml"/>
        <import resource="classpath:spring-service.xml"/>
        <import resource="classpath:spring-mvc.xml"/>
    
    </beans>
    
配置文件,暂时结束! Controller 和 视图层编写
  1. BookController类编写, 一、查询所有书籍

    @Controller
    @RequestMapping("/book")
    public class BookController {
    
        @Autowired
        @Qualifier("BookServiceImpl")
        private BookService bookService;
    
        /// 查询全部书籍,并发挥到一个书籍的展示页面
        @RequestMapping("/allBook")  //查询所有Book
        public String list(Model model){
            List<Books> list = bookService.queryAllBook();
            model.addAttribute("list",list);
            return "allBook";
        }
    
  2. 编写首页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>
    
  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 美化界面 --%>
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <%--    Bootstrap框架提供了更好的跨浏览器一致性 --%>
        <link href="../../css/normalize.css" rel="stylesheet">
    </head>
    <body>
    <%--边框线--%>
    <div class="container">
        <%-- 清除浮动--%>
        <div class="row clearfix">
        <%--    把一个列中等(md)屏幕(12份)分成12份     --%>
            <div class="col-md-12 column">
                <%-- 头部 标签--%>
                <div class="page-header">
                    <h1>
                        <small>书籍列表----显示所有书籍</small>
                    </h1>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 column">
                <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-4 column"></div>
            <div class="col-md-4 column">
                <%--  查询书籍  --%>
                <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
                    <span style="color: red; font-weight: bold">${error}</span>
                    <input type="text" name="queryBookName" placeholder="请输入要查询的书籍名称" required>
                    <input type="submit" value="查询" class="btn btn-primary">
                </form>
            </div>
        </div>
        <div class="row clearfix">
            <div class="col-md-12 column">
    <%--     table-hover:隔行变色     --%>
                <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="${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/toUpdateBook?id=${book.getBookID()}">修改</a> |&nbsp;
                                <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                 </tbody>
                </table>
            </div>
        </div>
    </div>
    </body>
    </html>
    
  4. 添加书籍

    //跳转到添加书籍页面(addBook.jsp)
        @RequestMapping("/toAddBook")
        public String toAddPaper(){
            return "addBook";
        }
    //  从addBook.jsp页面,返回的书籍数据,添加到数据库
    //添加书籍的请求
        @RequestMapping("/addBook")
        public String addPaper(Books books) {
            System.out.println("books==>"+books);
            bookService.addBook(books);
            return "redirect:/book/allBook";
        }
    
  5. addBook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>新增书籍</title>
        
        <!-- 引入 Bootstrap -->
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <link href="../../css/normalize.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="bkname">书籍名称:</label>
                <input type="text" class="form-control" id="bkname" name="bookName" required>
            </div>
            <div class="form-group">
                <label for="bknum">书籍数量:</label>
                <input type="text" class="form-control" id="bknum" name="bookCounts" required>
            </div>
            <div class="form-group">
                <label for="bkdetail">书籍描述:</label>
                <input type="text" class="form-control" id="bkdetail" name="detail" required>
            </div>
            <button type="submit" class="btn btn-primary">添加</button>
            <a href="${pageContext.request.contextPath}/book/allBook" class="btn btn-default">取消</a>
        </form>
    
    
    </div>
    </body>
    </html>
    
  6. 修改书籍

    /////   方法三:修改书籍
        // 先根据ID查询到书籍信息返回至修改页面,
        // 在updateBook页面 将id设为隐藏域,再将书籍信息更改后重定向到allBook
    
        @RequestMapping("/toUpdateBook")
        public String toUpdateBook(Model model,int id){
            Books books = bookService.queryBookById(id);
            System.out.println(books);
            model.addAttribute("book",books);
            return "updateBook";
        }
    
        @RequestMapping("/updateBook")
        public String updateBook(Model model,Books book){
            System.out.println("updateBook==>"+book);
            bookService.updateBook(book);
            Books books = bookService.queryBookById(book.getBookID());
            model.addAttribute("books",books);
            return "redirect:/book/allBook";
        }
    
  7. 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>
        
        <!-- 引入 Bootstrap -->
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <link href="../../css/normalize.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" method="post">
    <%--        修改书籍需要用到BookID  设置隐藏域   --%>
            <input type="hidden" name="bookID" value="${book.getBookID()}"/>
            <div class="from-group">
                <label>书籍名称:</label>
                <input  class="form-control" type="text" name="bookName" value="${book.getBookName()}" required/>
            </div>
            <div class="form-group">
                <label>书籍数量:</label>
                <input class="form-control" type="text" name="bookCounts" value="${book.getBookCounts()}" required/>
            </div>
            <div class="form-group">
                <label>书籍详情:</label>
                <input class="form-control" type="text" name="detail" value="${book.getDetail() }" required/>
            </div>
            <div class="form-group">
                <input class="form-control" type="submit" value="修改"/>
            </div>
            <div class="form-group">
                <a href="${pageContext.request.contextPath}/book/allBook" class="align-middle form-control">取消</a>
            </div>
        </form>
    
    </div>
    
  8. 删除书籍

    ////  方法四:  删除书籍
    
        @RequestMapping("/del/{bookId}")
        public String deleteBook(@PathVariable("bookId") int id){
            System.out.println("删除书籍的ID==>"+id);
            bookService.deleteBookById(id);
            return "redirect:/book/allBook";
        }
    
  9. 按书名查询书籍(找不到则显示全部书籍,并报错)

    ///查询书籍
    
        @RequestMapping("/queryBook")
        public String queryBook(String queryBookName,Model model){
    //        boolean q = false;
            List<Books> list = bookService.queryBookByName(queryBookName);
            for (Books books : list) {
                //红色输出
                System.err.println("queryBookName==>"+books);
            }
            if (list.size() == 0){
                list = bookService.queryAllBook();
                model.addAttribute("error","未查到");
                System.out.println("===未查到===");
            }
            model.addAttribute("list",list);
            return "allBook";
        }
    

小结(MySQL数据库主键无法连续自增问题)

MySQL数据库:

​ 解决单条数据id自增不连续问题

​ 创建的表的类型为InnoDB类型,为了提升性能设置AUTO_INCREMNT不会回退,因此innoDB使用了不连续的自增值

image-20201112102448947

解决:

​ 使用Mybatis中的标签

<!-- 当用户表为空时,id设置为1
当用户表不为空时,id设置为当前最大id加1   -->
    <insert id="addBook" parameterType="Books">
        <selectKey keyProperty="bookID" resultType="int" order="BEFORE">
            select if(max(bookID) is null,1,max(bookID)+1) as bookID from books
        </selectKey>
        insert into books (bookID,bookName,bookCounts,detail)
        values (#{bookID},#{bookName},#{bookCounts},#{detail});
    </insert>

image-20201112102517207

 

posted @ 2021-02-16 12:57  李海家  阅读(57)  评论(0编辑  收藏  举报