zoukankan      html  css  js  c++  java
  • springMVC阶段性学习--书籍管理

     

    1、前情提要:

    注意事项:

      ①将maven项目添加web框架

      ②项目结构新建lib包导入所有依赖(此步请在pom.cml导入依赖后完成)

       ③配置Tomcat

      ④项目结构概览

      ⑤数据库

    2、文件配置

      2.1 pom.xml   配置依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.meng</groupId>
        <artifactId>springmvc-ssm-mybatis</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <!--数据库驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.21</version>
            </dependency>
            <!--数据库连接池-->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.3</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2.1-b03</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.5</version>
            </dependency>
            <!--spring-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.7.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.8.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
            </dependency>
        </dependencies>
        <!--静态资源导出问题-->
        <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>
    
    
    </project>
    View Code

      2.2 database.properties (配置mysql)

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=Asia/Shanghai&useSSL=true&useUnicode=true&characterEncoding=utf8&userSSL=false&serverTimezone=GMT%2B8
    jdbc.username=root
    jdbc.password=123456
    View Code

      2.3 mybatis-config.xml (整合mybatis映射mysql)

    <?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>
    
        <typeAliases>
            <package name="com.meng.pojo"/>
        </typeAliases>
    
        <mappers>
            <mapper class="com.meng.dao.BookMapper"/>
        </mappers>
        
    </configuration>
    View Code

      2.4 spring-dao.xml (持久层dao配置)

    <?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">
        <!-- 配置整合mybatis -->
        <!-- 1.关联数据库文件 -->
        <context:property-placeholder  location="classpath:database.properties"/>
        <!-- 2.数据库连接池 -->
        <!--数据库连接池 dbcp 半自动化操作 不能自动连接
                        c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)-->
        <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"/>
            <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
        <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
        <!--解释 : https://www.cnblogs.com/jpfss/p/7799806.html-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 注入sqlSessionFactory -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!-- 给出需要扫描Dao接口包 -->
            <property name="basePackage" value="com.meng.dao"/>
        </bean>
    </beans>
    View Code

      2.5 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: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">
    
        <!--注解驱动-->
        <mvc:annotation-driven/>
        <!--静态资源过滤-->
        <mvc:default-servlet-handler/>
        <!--扫描包-->
        <context:component-scan base-package="com.meng.controller"/>
        <!--视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
    </beans>
    View Code

      2.6 spring-service.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           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">
    
    
        <!-- 扫描service相关的bean -->
        <context:component-scan base-package="com.meng.service" />
        <!--BookServiceImpl注入到IOC容器中-->
        <bean id="BookServiceImpl" class="com.meng.service.BookServiceImpl">
            <property name="bookMapper" ref="bookMapper"/>
        </bean>
        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        </bean>
    </beans>
    View Code

      2.7 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>
    View Code

      2.8 /WEB-INF/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">
        <!--DispatchService-->
        <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-config>
            <session-timeout>15</session-timeout>
        </session-config>
    </web-app>
    View Code

     3、dao层

      3.1 BookMapper

    package com.meng.dao;
    
    import com.meng.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    public interface BookMapper {
    
        int addBook(Books books);
        //@Param用于传递参数,从而可以与SQL中的的字段名相对应
        int deleteBookById(@Param("bookID") int id);
    
        int updateBook(Books books);
    
        Books queryBookById(@Param("bookID") int id);
    
        List<Books> queryAllBook();
    
        Books queryBookByName(String bookName);
    }
    View Code

      3.2 BookMapper.xml 配置 (执行数据库操作)

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.meng.dao.BookMapper">
    
        <insert id="addBook" parameterType="Books">
            insert into books(bookName,bookCounts,detail) value (#{bookName},#{bookCounts},#{detail})
        </insert>
    
        <delete id="deleteBookById" parameterType="int" >
            delete from books where bookID=#{bookID}
        </delete>
    
        <update id="updateBook" parameterType="Books">
            update books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail} where bookID=#{bookID}
        </update>
        
        <select id="queryBookById" resultType="Books">
            select * from books where bookID = #{bookID}
        </select>
    
        <select id="queryAllBook"  resultType="Books">
            SELECT * FROM books
        </select>
    
        <select id="queryBookByName" resultType="Books" >
            select * from books where bookName = #{bookName}
        </select>
    
    </mapper>
    View Code

    4、pojo层

      Books类    

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

    5、service层

      5.1 接口 BookService

    package com.meng.service;
    
    import com.meng.pojo.Books;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    @Service
    public interface BookService {
        //增加Book
        int addBook(Books books);
        //根据id删除Book
        int deleteBookById( int id);
        //更新一个Book
        int updateBook(Books books);
        //根据id查询返回一个Book
        Books queryBookById(int id);
        //查询所有Book返回到list集合中
        List<Books> queryAllBook();
    
        Books queryBookByName(String bookName);
    }
    View Code

      5.2 实现类 BookServiceImpl  (代理层代理数据库操作)

    package com.meng.service;
    
    import com.meng.dao.BookMapper;
    import com.meng.pojo.Books;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import java.util.List;
    
    public class BookServiceImpl implements BookService {
        @Autowired
        //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 deleteBookById(int id) {
            return bookMapper.deleteBookById(id);
        }
    
        public int updateBook(Books books) {
            return bookMapper.updateBook(books);
        }
    
        public Books queryBookById(int id) {
            return bookMapper.queryBookById(id);
        }
    
        public List<Books> queryAllBook() {
            return bookMapper.queryAllBook();
        }
    
        public Books queryBookByName(String bookName){
            return bookMapper.queryBookByName(bookName);
        }
    }
    View Code

    6、controller层

      BookController类   (主要面向前端强求)

    package com.meng.controller;
    
    import com.meng.pojo.Books;
    import com.meng.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.awt.print.Book;
    import java.util.ArrayList;
    import java.util.List;
    
    @Controller
    @RequestMapping("/book")
    public class BookController {
        @Autowired
        @Qualifier("BookServiceImpl")
        private BookService bookService;
    //    查询全部书籍返货页面
        @RequestMapping("/allBook")
        public String list(Model model){
            List<Books> list =bookService.queryAllBook();
            model.addAttribute("list",list);
            return "allBook";
        }
    
        //增加书籍页面
        @RequestMapping("/toAddBook")
        public String toAddPaper(){
            return "addBook";
        }
        //添加书籍请求
        @RequestMapping("/addBook")
        public String addBook(Books books){
            System.out.println("addBook===>"+books);
            bookService.addBook(books);
            //添加书籍之后重定向回到aaBook页面
            return "redirect:/book/allBook";
        }
    
        //跳转到修改页面
        @RequestMapping("/toUpdate")
        public String toUpdatePaper(int id,Model model){
            Books books = bookService.queryBookById(id);
            model.addAttribute("QBook",books);
            System.out.println(id);
            return "updateBook";
        }
    
        //修改书籍
        @RequestMapping("/update")
        public String updateBook(Books books){
            System.out.println("updateBook=="+books);
            bookService.updateBook(books);
            return "redirect:/book/allBook";
        }
    
        //删除书籍
        @RequestMapping("/deleteBookById/{bookID}")
        public String deleteBookById(@PathVariable("bookID") int id){
            bookService.deleteBookById(id);
            return "redirect:/book/allBook";
        }
    
        //书籍查询
        @RequestMapping("/queryBookByName")
        public String queryBook(String queryBookName,Model model){
            System.out.println("查询书籍:"+queryBookName);
            Books books = bookService.queryBookByName(queryBookName);
            List<Books> list = new ArrayList<Books>();
            list.add(books);
            if (books==null){
                list = bookService.queryAllBook();
                model.addAttribute("error","没有找到书籍!");
            }
            model.addAttribute("list",list);
            return "allBook";
        }
    
    
    }
    View Code

    7、前端jsp页面

      7.1 欢迎页 index.jsp

    <%--
      Created by IntelliJ IDEA.
      User: MJZ
      Date: 2020/8/13
      Time: 10:09
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <style type="text/css">
          html{height: 100%;}
          body{
            background-image: url("11.jpg");
            background-size: 100% 100%;
            padding: 0;
            margin: 0;
          }
        </style>
        <title>首页</title>
        <style>
          a{
            text-decoration: none;
            color: black;
            font-size: 18px;
          }
          h3{
            width: 180px;
            height: 30px;
            margin: 100px auto;
            text-align: center;
            line-height: 30px;
            background: deepskyblue;
            border-radius: 10px;
          }
        </style>
      </head>
      <body>
      <h3>
        <%--${pageContext.request.contextPath}取绝对地址--%>
        <a href="${pageContext.request.contextPath}/book/allBook">进入书籍界面</a>
      </h3>
      </body>
    </html>
    View Code

      7.2 /WEB-INF/jsp包下的addBook.jsp

    <%--
      Created by IntelliJ IDEA.
      User: MJZ
      Date: 2020/8/13
      Time: 10:09
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <style type="text/css">
          html{height: 100%;}
          body{
            background-image: url("11.jpg");
            background-size: 100% 100%;
            padding: 0;
            margin: 0;
          }
        </style>
        <title>首页</title>
        <style>
          a{
            text-decoration: none;
            color: black;
            font-size: 18px;
          }
          h3{
            width: 180px;
            height: 30px;
            margin: 100px auto;
            text-align: center;
            line-height: 30px;
            background: deepskyblue;
            border-radius: 10px;
          }
        </style>
      </head>
      <body>
      <h3>
        <%--${pageContext.request.contextPath}取绝对地址--%>
        <a href="${pageContext.request.contextPath}/book/allBook">进入书籍界面</a>
      </h3>
      </body>
    </html>
    View Code

      7.3 /WEB-INF/jsp包下的allBook.JSP

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%--
      Created by IntelliJ IDEA.
      User: MJZ
      Date: 2020/8/13
      Time: 11:09
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <title>书籍展示</title>
        <div class="container">
    
            <div class="row-clearfix">
                <div class="col-md-12 colum">
                    <div class="page-header">
                        <h1>
                            <small>书籍列表</small>
                        </h1>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 colum">
                        <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 colum"></div>
                    <div class="col-md-4 colum">
                        <form action="${pageContext.request.contextPath}/book/queryBookByName" method="get" class="form-inline" style="float:right">
                            <input type="submit" value="查询" class="btn btn-primary">
                            <input type="text" name="queryBookName" class="form-control" placeholder="请输入书籍名称">
                        </form>
                    </div>
                </div>
            </div>
            <div class="row clearfix">
                <div class="col-md-12 colum">
                    <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.bookID}</td>
                                    <td>${book.bookName}</td>
                                    <td>${book.bookCounts}</td>
                                    <td>${book.detail}</td>
                                    <td>
                                        <a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改</a>
                                        &nbsp; | &nbsp;
                                        <a href="${pageContext.request.contextPath}/book/deleteBookById/${book.bookID}">删除</a>
                                    </td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </head>
    <body>
    <h1></h1>
    </body>
    </html>
    View Code

      7.4 /WEB-INF/jsp包下的updateBook.JSP

    <%--
      Created by IntelliJ IDEA.
      User: MJZ
      Date: 2020/8/13
      Time: 16:23
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>修改书籍</title>
    
        <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 colum">
                <div class="page-header">
                    <h1>
                        <small>修改书籍</small>
                    </h1>
                </div>
            </div>
        </div>
        <form action="${pageContext.request.contextPath}/book/update" method="post">
            <%--容易出现的问题:更新需要依据id,但是id没有传回后台,所以更新不了,sql执行不了--%>
            <%--使用隐藏域传id--%>
            <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="from-group">
                <input type="submit" class="form-control" value="修改">
            </div>
        </form>
    </div>
    </body>
    </html>
    View Code
  • 相关阅读:
    Objective C 绘制透明窗口的方法
    在挂载的 NTFS 盘上运行 gdb 会遇到权限问题,导致无法初始化
    使用 Eclipse 打造 操作系统实习 JOS 开发环境
    C# URL 中文编码与解码
    突破教育网的防线,将搜狗浏览器的教育网加速功能全面推向各种浏览器
    linux 截屏工具
    yum install 时 提示某个已安装的库(x86_64)比某个要安装的库(i686) 新导致安装失败
    全方位打造 Eclipse 自定义开发环境
    自动售饮料机的verilog实现
    数字跑表的verilog实现
  • 原文地址:https://www.cnblogs.com/Meng2113/p/13502269.html
Copyright © 2011-2022 走看看