• 九、SpringMVC(3)


    一 、整合SSM

    最终整合结构参考 🌻🌻

    在这里插入图片描述

    1.1 环境要求

    (1)环境

    • IDEA
    • MySQL 5.7.19
    • Tomcat 9
    • Maven 3.6

    (2)要求

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

    1.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,'从进门到进牢');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    1.3 基本环境搭建

    1. 新建一Maven项目!ssmbuild , 添加web的支持
    2. 导入相关的pom依赖!
    <dependencies>
       
       <dependency>
           <groupId>junitgroupId>
           <artifactId>junitartifactId>
           <version>4.12version>
       dependency>
       
       <dependency>
           <groupId>mysqlgroupId>
           <artifactId>mysql-connector-javaartifactId>
           <version>5.1.47version>
       dependency>
       
       <dependency>
           <groupId>com.mchangegroupId>
           <artifactId>c3p0artifactId>
           <version>0.9.5.2version>
       dependency>
    
       
       <dependency>
           <groupId>javax.servletgroupId>
           <artifactId>servlet-apiartifactId>
           <version>2.5version>
       dependency>
       <dependency>
           <groupId>javax.servlet.jspgroupId>
           <artifactId>jsp-apiartifactId>
           <version>2.2version>
       dependency>
       <dependency>
           <groupId>javax.servletgroupId>
           <artifactId>jstlartifactId>
           <version>1.2version>
       dependency>
    
       
       <dependency>
           <groupId>org.mybatisgroupId>
           <artifactId>mybatisartifactId>
           <version>3.5.2version>
       dependency>
       <dependency>
           <groupId>org.mybatisgroupId>
           <artifactId>mybatis-springartifactId>
           <version>2.0.2version>
       dependency>
    
       
       <dependency>
           <groupId>org.springframeworkgroupId>
           <artifactId>spring-webmvcartifactId>
           <version>5.1.9.RELEASEversion>
       dependency>
       <dependency>
           <groupId>org.springframeworkgroupId>
           <artifactId>spring-jdbcartifactId>
           <version>5.1.9.RELEASEversion>
       dependency>
       <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.24version>
       dependency>
    dependencies>
    
    • 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
    1. Maven资源过滤设置
    <build>
       <resources>
           <resource>
               <directory>src/main/javadirectory>
               <includes>
                   <include>**/*.propertiesinclude>
                   <include>**/*.xmlinclude>
               includes>
               <filtering>falsefiltering>
           resource>
           <resource>
               <directory>src/main/resourcesdirectory>
               <includes>
                   <include>**/*.propertiesinclude>
                   <include>**/*.xmlinclude>
               includes>
               <filtering>falsefiltering>
           resource>
       resources>
    build>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    1. 建立基本结构和配置框架!👇🏾👇🏾
    • com.zql.pojo
    • com.zql.dao
    • com.zql.service
    • com.zql.controller
    • mybatis-config.xml 👇🏾👇🏾
    
    DOCTYPE configuration
           PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
           "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • applicationContext.xml 👇🏾👇🏾
    
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.4 Mybatis 层编写

    1. 数据库配置文件 database.properties
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=root
    
    • 1
    • 2
    • 3
    • 4
    1. IDEA关联数据库
    2. 编写MyBatis的核心配置文件 👇🏾👇🏾
    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <typeAliases>
            <package name="com.zql.pojo"/>
        typeAliases>
    
        <mappers>
            <mapper class="com.zql.dao.BooksMapper"/>
        mappers>
    
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    1. 编写数据库对应的实体类 com.zql.pojo.Books (使用lombok插件!)
    package com.zql.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.io.Serializable;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Books implements Serializable {
    
        private int bookID;
    
        private String bookName;
    
        private int bookCounts;
    
        private String detail;
    }
    
    • 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
    1. 编写Dao层的 Mapper接口!BooksMapper.java
    package com.zql.dao;
    
    import com.zql.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    import org.springframework.web.bind.annotation.PathVariable;
    
    import java.util.List;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    public interface BooksMapper {
    
        //增加一本书籍
        int addBooks(Books books);
        //删除一本书根据id
        int deleteBooksById(@Param("bookID") int bookID);
        //修改一本书
        int updateBooks(Books books);
        //根据id查询一本书
        Books queryById(@Param("bookID") int bookID);
        //查询所有的书
        List<Books> queryAllBooks();
        //根据书籍名称查询书籍
        Books queryByBookName(@Param("bookName") String bookName);
    }
    
    • 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
    1. 编写接口对应的 Mapper.xml 文件;BooksMapper.xml
    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.zql.dao.BooksMapper">
    
        
        <insert id="addBooks" parameterType="Books">
            insert into ssmbuild.books (bookName, bookCounts, detail)
            values (#{bookName}, #{bookCounts}, #{detail});
        insert>
    
        
        <delete id="deleteBooksById" parameterType="int">
            delete from ssmbuild.books where bookID=#{bookID}
        delete>
    
        
        <update id="updateBooks" parameterType="Books">
            update ssmbuild.books set
            bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}
        update>
    
       
        <select id="queryById" resultType="Books">
            select * from ssmbuild.books where bookID=#{bookID}
        select>
        
        <select id="queryAllBooks" resultType="Books">
            select * from ssmbuild.books;
        select>
        
        <select id="queryByBookName" resultType="Books">
            select * from ssmbuild.books where bookName=#{bookName}
        select>
    mapper>
    
    • 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
    1. 编写Service层的接口和实现类

    接口 BooksService.java

    package com.zql.service;
    
    import com.zql.pojo.Books;
    import org.springframework.web.bind.annotation.PathVariable;
    
    import java.util.List;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    public interface BooksService {
    
        //增加一本书籍
        int addBooks(Books books);
        //删除一本书根据id
        int deleteBooksById(int bookID);
        //修改一本书
        int updateBooks(Books books);
        //根据id查询一本书
        Books queryById(int bookID);
        //查询所有的书
        List<Books> queryAllBooks();
        //根据书籍名称查询书籍
        Books queryByBookName(String bookName);
    }
    
    • 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

    实现类 BooksServiceImpl.java

    package com.zql.service;
    
    import com.zql.dao.BooksMapper;
    import com.zql.pojo.Books;
    
    import java.util.List;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    public class BooksServiceImpl implements BooksService {
        //调用dao层的操作,设置一个set接口,方便Spring管理
        private BooksMapper booksMapper;
    
        public void setBooksMapper(BooksMapper booksMapper) {
            this.booksMapper = booksMapper;
        }
    
        @Override
        public int addBooks(Books books) {
            return booksMapper.addBooks(books);
        }
    
        @Override
        public int deleteBooksById(int bookID) {
            return booksMapper.deleteBooksById(bookID);
        }
    
        @Override
        public int updateBooks(Books books) {
            return booksMapper.updateBooks(books);
        }
    
        @Override
        public Books queryById(int bookID) {
            return booksMapper.queryById(bookID);
        }
    
        @Override
        public List<Books> queryAllBooks() {
            return booksMapper.queryAllBooks();
        }
        @Override
        public Books queryByBookName(String bookName) {
            return booksMapper.queryByBookName(bookName);
        }
    }
    
    • 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

    1.5 Spring 层编写

    1. 配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;
    2. 我们去编写Spring整合Mybatis的相关的配置文件;spring-dao.xml
    
    <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="classpath:database.properties"/>
        
        
        <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}"/>
            
            <property name="maxPoolSize" value="30"/>
            <property name="minPoolSize" value="10"/>
            
            <property name="autoCommitOnClose" value="false"/>
            
            <property name="checkoutTimeout" value="10000"/>
            
            <property name="acquireRetryAttempts" value="2"/>
        bean>
        
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            
            <property name="dataSource" ref="dataSource"/>
            
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        bean>
    
        
        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            
            <context:component-scan base-package="com.zql.dao"/>
        bean>
    beans>
    
    • 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
    1. Spring整合service层 spring-service.xml
    
    <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">
    
    
        
        <context:component-scan base-package="com.zql.service"/>
    
        
        
        <bean id="BooksServiceImpl" class="com.zql.service.BooksServiceImpl">
            <property name="booksMapper" ref="booksMapper"/>
        bean>
    
        
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            
            <property name="dataSource" ref="dataSource"/>
        bean>
    
        
    
    beans>
    
    • 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

    报红:👇🏾👇🏾

    在这里插入图片描述
    解决:👇🏾👇🏾

    方式一:

    spring-service.xml直接加 👇🏾👇🏾

    <import resource="classpath:spring-dao.xml"/>
    
    • 1

    方式二:
    在这里插入图片描述
    添加成功查看:👇🏾👇🏾
    在这里插入图片描述
    Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器!对吧!

    1.6 SpringMVC 层编写

    1. web支持 👇🏾👇🏾

    在这里插入图片描述

    2. web.xml

    
    <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">
    
        
        <servlet>
            <servlet-name>springmvcservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:spring-mvc.xmlparam-value>
            init-param>
            <load-on-startup>1load-on-startup>
        servlet>
    
        <servlet-mapping>
            <servlet-name>springmvcservlet-name>
            <url-pattern>/*url-pattern>
        servlet-mapping>
    
        
        <filter>
            <filter-name>encodingFilterfilter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
            <init-param>
                <param-name>encodingparam-name>
                <param-value>utf-8param-value>
            init-param>
        filter>
        <filter-mapping>
            <filter-name>encodingFilterfilter-name>
            <url-pattern>/*url-pattern>
        filter-mapping>
    
        
        <session-config>
            <session-timeout>15session-timeout>
        session-config>
    web-app>
    
    • 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
    1. spring-mvc.xml
    
    <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">
    
        
        
        <mvc:annotation-driven/>
        
        <mvc:default-servlet-handler/>
    
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              id="internalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        bean>
    
        
        <context:component-scan base-package="com.zql.controller"/>
    beans>
    
    • 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
    1. Spring配置整合文件,applicationContext.xml
    
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    1. 测试是否整合成功 👇🏾👇🏾

    创建 MyTest.java

    import com.zql.pojo.Books;
    import com.zql.service.BooksService;
    import com.zql.service.BooksServiceImpl;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import java.util.List;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    public class MyTest {
    
        @Test
        public void test(){
    
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            BooksService booksServiceImpl = (BooksService) context.getBean("BooksServiceImpl");
    
            for (Books books : booksServiceImpl.queryAllBooks()) {
    
                System.out.println(books);
            }
        }
    }
    
    • 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

    参考 👉🏾👉🏾 导入依赖并且启动tomcat

    在这里插入图片描述

    整合完毕 !!! ✌✌✌

    二、编写 CRUD

    Controller 和 视图层编写

    2.1 方法一:查询全部书籍

    1. BookController 类编写 BooksController.java
    package com.zql.controller;
    
    import com.zql.pojo.Books;
    import com.zql.service.BooksService;
    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 org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    
    @Controller
    @RequestMapping("/books")
    public class BooksController {
    
        @Autowired
        @Qualifier("BooksServiceImpl")
        private BooksService booksService;
    
        @RequestMapping("/booksAll")
        public String queryAllBooks(Model model){
    
            List<Books> books = booksService.queryAllBooks();
    
            model.addAttribute("books",books);
    
            return "/allBooks";
        }
    }
    
    
    • 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
    1. 编写首页 index.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
      </head>
      <body>
      <a href="${pageContext.request.contextPath}/books/booksAll">进入书籍页面</a>
      </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 书籍列表页面 WEB-INF/jsp/allBooks.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    书籍页面
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    启动tomcat 👇🏾👇🏾
    在这里插入图片描述

    分析:👇🏾👇🏾

    1. 查看这个bean注入是否成功!
    2. Junit单元测试,看我们的代码是否能够查询出来结果! ok
    3. 问题,一定不在我们的底层,是spring出了问题!
    4. SpringMVC,整合的时候没调用到我们的service层的bean:
      – (1) applicationContext.xml没有注入bean
      – (2) web.xml中,我们绑定过配置文件,发现问题,我们配置的是spring-mvc.xml,这里确实没有 service bean,所以报空指针

    解决 (改动如下):👇🏾👇🏾
    在这里插入图片描述

    再次启动tomcat 成功显示 👇🏾👇🏾

    在这里插入图片描述
    优化上述2&3页面👇🏾👇🏾

    1. 编写首页 index.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <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}/books/booksAll">点击进入列表页面</a>
      </h3>
      </body>
    </html>
    
    
    • 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
    1. 书籍列表页面 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, initial-scale=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}/books/toAddPage">新增</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="${books}"><%--方式二写法:requsestScope.get('books')--%>
                        <tr>
                            <td>${book.bookID}</td>
                            <td>${book.bookName}</td>
                            <td>${book.bookCounts}</td>
                            <td>${book.detail}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/books/toUpdatePage?bookID=${book.bookID}">更改</a>
                                <a href="${pageContext.request.contextPath}/books/deleteBooksById/${book.bookID}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    </body>
    </html>
    
    • 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

    在这里插入图片描述

    2.2 方法二:添加书籍

    1. BookController 类编写
     //跳转到添加页面
     @RequestMapping("/toAddPage")
     public String toAddPage(){
         return "addBooks";
     }
    
     //添加书籍
     @RequestMapping("/addBooks")
     public String addBooks(Books books){
    
         booksService.addBooks(books);
    
         return "redirect:/books/booksAll";
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    1. 添加书籍页面:WEB-INF/jsp/addBooks.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, initial-scale=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}/books/addBooks" method="post">
            书籍名称:<input type="text" name="bookName"><br><br><br>
            书籍数量:<input type="text" name="bookCounts"><br><br><br>
            书籍详情:<input type="text" name="detail"><br><br><br>
            <input type="submit" value="添加">
        </form>
    </div>
    
    • 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

    2.3 方法三:修改书籍

    1. BookController 类编写
    //跳转到修改页面并回显
    @RequestMapping("/toUpdatePage")
    public String toUpdatePage(Model model,int bookID){
        Books books = booksService.queryById(bookID);
    
        model.addAttribute("books",books);
    
        return "updateBooks";
    }
    
    //修改书籍
    @RequestMapping("/updateBooks")
    public String updateBooks(Model model,Books books){
    
        booksService.updateBooks(books);
    
        Books books1 = booksService.queryById(books.getBookID());
    
        model.addAttribute("books1",books1);
        return "redirect:/books/booksAll";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    1. 修改书籍页面 WEB-INF/jsp/updateBooks.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, initial-scale=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}/books/updateBooks" method="post">
            <input type="hidden" name="bookID" value="${books.bookID}"/>
            书籍名称:<input type="text" name="bookName" value="${books.bookName}"/><br/><br/>
            书籍数量:<input type="text" name="bookCounts" value="${books.bookCounts}"/><br/><br/>
            书籍详情:<input type="text" name="detail" value="${books.detail}"/><br/><br/>
            <input type="submit" value="提交"/>
        </form>
    
    </div>
    
    • 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

    在这里插入图片描述

    2.4 方法四:删除书籍

    1. BookController 类编写
     //删除书籍
     @RequestMapping("/deleteBooksById/{bookID}")
     public String deleteBooksById(@PathVariable("bookID") int id){ //Restful风格
    
         booksService.deleteBooksById(id);
    
         return "redirect:/books/booksAll";
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    在这里插入图片描述

    2.5 方法五:根据书籍名称查询书籍

    1. BookController 类编写
    	//根据书籍名称查询书籍
    	@RequestMapping("/queryByBookName")
    	public String queryByBookName(Model model,String queryByBookName){
    	
    		  Books books1 = booksService.queryByBookName(queryByBookName);
    		
    		  List<Books> books = new ArrayList<>();
    		
    		  books.add(books1);
    		
    		  if(books1 == null){
    		      books = booksService.queryAllBooks();
    		      model.addAttribute("msg","未查到");
    		  }
    		
    		  model.addAttribute("books",books);
    		
    		  return "allBooks";
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    1. 书籍列表页面 allbook.jsp
    <%--查询根据name--%>
    <div class="col-md-4 column">
       <form class="navbar-form navbar-left" action="${pageContext.request.contextPath}/books/queryByBookName" method="post">
           <div class="form-group">
               <span style="color: red;font-weight: bold">${msg}</span>
               <input type="text" name="queryByBookName" class="form-control" placeholder="请输入要查询的书籍名称">
           </div>
           <button type="submit" class="btn btn-primary">查询</button>
       </form>
    </div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    完整代码:👇🏾👇🏾

    <%@ 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, initial-scale=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}/books/toAddPage">新增</a>
            </div>
            <%--查询根据name--%>
            <div class="col-md-4 column">
                <form class="navbar-form navbar-left" action="${pageContext.request.contextPath}/books/queryByBookName" method="post">
                    <div class="form-group">
                        <span style="color: red;font-weight: bold">${msg}</span>
                        <input type="text" name="queryByBookName" class="form-control" placeholder="请输入要查询的书籍名称">
                    </div>
                    <button type="submit" class="btn btn-primary">查询</button>
                </form>
            </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="${books}"><%--方式二写法:requsestScope.get('books')--%>
                        <tr>
                            <td>${book.bookID}</td>
                            <td>${book.bookName}</td>
                            <td>${book.bookCounts}</td>
                            <td>${book.detail}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/books/toUpdatePage?bookID=${book.bookID}">更改</a>
                                <a href="${pageContext.request.contextPath}/books/deleteBooksById/${book.bookID}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    </body>
    </html>
    
    • 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
    • 68
    • 69
    • 70
    • 71

    启动tomcat 👇🏾👇🏾
    在这里插入图片描述
    在这里插入图片描述

    项目结构图

    在这里插入图片描述
    在这里插入图片描述

    SpringMVC案例所有源码

  • 相关阅读:
    驱动9.07
    JavaSE总目录(梦的开始)
    安全模型在企业中的应用
    MySQL笔记:MySQL求最近一段时间
    极智嘉(Geek+)官宣重磅合作伙伴,再度赋能仓储自动化解决方案落地
    小红书种草推广步骤是怎样的,小红书种草效果好吗?
    梦想照进现实
    达梦SQL语法兼容笔记
    g.Grafana之Gauge的图形说明
    RabbitMQ初步到精通-第八章-Java-AMQP-Client源码分析
  • 原文地址:https://blog.csdn.net/weixin_42171159/article/details/126017591