0


Sprig框架集成(SSM框架) | Sping+SpringMVC+Mybatis

SSM框架

在这里插入图片描述

SSM是sping+springMVC+mybatis集成的框架:标准的MVC模式,整个系统划分为表现层,controller层,service层,DAO层四层

  • Spring(业务层)Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new一个对象,而是让Spring框架帮你来完成这一切。
  • SpringMVC(表示层)SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
  • Mybatis(持久层)mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。页面发送请求给控制器,控制器调用业务层处理逻辑,逻辑层向持久层发送请求,持久层与数据库交互,后将结果返回给业务层,业务层将处理逻辑发送给控制器,控制器再调用视图展现数据

项目结构

在这里插入图片描述

SSM整合

Mybatis层

配置

  • 数据库环境配置
CREATEDATABASE`SSMBuild`;USE`SSMBuild`;DROPTABLEIFEXISTS`books`;CREATETABLE`books`(`bookID`INT(10)NOTNULLAUTO_INCREMENTCOMMENT'书id',`bookName`VARCHAR(100)NOTNULLCOMMENT'书名',`bookCounts`INT(11)NOTNULLCOMMENT'数量',`detail`VARCHAR(200)NOTNULLCOMMENT'描述',KEY`bookID`(`bookID`))ENGINE=INNODBDEFAULTCHARSET= utf8;INSERTINTO`books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES(1,'Java',1,'从入门到放弃'),(2,'MySQL',10,'从删库到跑路'),(3,'Linux',5,'从进门到进牢');
  • pom.xml配置
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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>org.example</groupId><artifactId>SSMBuild</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><!--依赖导入--><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.49</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><!--Lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</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>

resources包

  • mybatis-config.xml(mybatis核心配置文件)
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!--配置数据源,Spring操作--><!--typeAliases:它仅用于XML配置,意在降低冗余的全限定类名书写--><typeAliases><packagename="com.wei.pojo"/></typeAliases><!-- 使用映射器接口实现类的完全限定类名 --><mappers><mapperclass="com.wei.dao.BookMapper"/></mappers></configuration>
  • applicationContext.xml(spring核心配置文件)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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>
  • database.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
jdbc.username=root
jdbc.password=root

java包

  • com.wei.pojo.Books(数据库对应的实体类 )
packagecom.wei.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructorpublicclassBooks{privateint bookID;privateString bookName;privateint bookCounts;privateString detail;}
  • com.wei.dao.BookMapper(编写Dao层的 Mapper接口)
packagecom.wei.dao;importcom.wei.pojo.Books;importorg.apache.ibatis.annotations.Param;importjava.util.List;publicinterfaceBookMapper{//增加一本书intaddBook(Books books);//删除一本书,@Param注解给参数命名intdeleteBookById(@Param("bookId")int id);//更新一本书intupdateBook(Books books);//查询一本书BooksqueryBookById(@Param("bookId")int id);//查询全部书List<Books>queryAllBook();}
  • com.wei.pojo.BooksMapper.xml(编写接口对应的 Mapper.xml 映射文件,导入MyBatis的包)
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.wei.dao.BookMapper"><insertid="addBook"parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert><deleteid="deleteBookById"parameterType="int">
        delete from ssmbuild.books where bookID=#{bookId}
    </delete><updateid="updateBook"parameterType="Books">
        update ssmbuild.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookID};
    </update><selectid="queryBookById"parameterType="int"resultType="Books">
        select * from ssmbuild.books where bookID=#{bookID};
    </select><selectid="queryAllBook"resultType="Books">
        select * from ssmbuild.books;
    </select></mapper>
  • 编写Service层的接口
packagecom.wei.service;importcom.wei.pojo.Books;importorg.apache.ibatis.annotations.Param;importjava.util.List;publicinterfaceBookService{//增加一本书intaddBook(Books books);//删除一本书,@Param注解给参数命名intdeleteBookById(int id);//更新一本书intupdateBook(Books books);//查询一本书BooksqueryBookById(int id);//查询全部书List<Books>queryAllBook();}
  • 编写Service层的实现类
packagecom.wei.service;importcom.wei.dao.BookMapper;importcom.wei.pojo.Books;importjava.util.List;publicclassBookServiceImplimplementsBookService{//调用dao层的操作,设置一个set接口,方便Spring管理privateBookMapper bookMapper;publicvoidsetBookMapper(BookMapper bookMapper){this.bookMapper = bookMapper;}@OverridepublicintaddBook(Books books){return bookMapper.addBook(books);}@OverridepublicintdeleteBookById(int id){return bookMapper.deleteBookById(id);}@OverridepublicintupdateBook(Books books){return bookMapper.updateBook(books);}@OverridepublicBooksqueryBookById(int id){return bookMapper.queryBookById(id);}@OverridepublicList<Books>queryAllBook(){return bookMapper.queryAllBook();}}

Spring层

resource包

  • spring-dao.xml(spring整合dao层)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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"><!--关联数据库配置文件:Spring读取数据库配置文件--><context:property-placeholderlocation="classpath:database.properties"/><!--连接池:
    dbcp:半自动化操作,不能自动连接
    c3p0:自动化操作,自动化的加载配置文件,并且可以自动设置到对象中
    druid、hikari--><!--
    dbcp:
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    --><!--c3p0--><beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"><propertyname="driverClass"value="${jdbc.driver}"/><propertyname="jdbcUrl"value="${jdbc.url}"/><propertyname="user"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/><!-- c3p0连接池的私有属性 --><propertyname="maxPoolSize"value="30"/><propertyname="minPoolSize"value="10"/><!-- 关闭连接后不自动commit --><propertyname="autoCommitOnClose"value="false"/><!-- 获取连接超时时间 --><propertyname="checkoutTimeout"value="10000"/><!-- 当获取连接失败重试次数 --><propertyname="acquireRetryAttempts"value="2"/></bean><!--配置SqlSessionFactory对象--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入数据库连接池 --><propertyname="dataSource"ref="dataSource"/><!-- 配置MyBaties全局配置文件:mybatis-config.xml --><propertyname="configLocation"value="classpath:mybatis-config.xml"/></bean><!--配置dao接口扫描包:动态实现Dao接口注入Spring容器--><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/><propertyname="sqlSessionTemplateBeanName"value="sqlSessionFactory"/><!--要扫描的包--><propertyname="basePackage"value="com.wei.dao"/></bean></beans>
  • spring-service.xml(Spring整合service层)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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下的包--><context:component-scanbase-package="com.wei.service"/><!--将所有业务类注入Spring,可以通过配置或者注解--><beanid="BookServiceImpl"class="com.wei.service.BookServiceImpl"><propertyname="bookMapper"ref="bookMapper"/></bean><!--声明式事务管理--><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--注入数据源--><propertyname="dataSource"ref="dataSource"/></bean></beans>

SpringMVC层

添加web支持

  • web.xml
<?xml version="1.0" encoding="UTF-8"?><web-appxmlns="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>
  • spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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/cache/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/><!--扫描包:controller--><context:component-scanbase-package="com.wei.controller"/><!--视图解析器--><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="prefix"value="/WEB-INF/jsp/"/><propertyname="suffix"value=".jsp"/></bean></beans>
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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"><importresource="classpath:spring-dao.xml"/><importresource="classpath:spring-service.xml"/><importresource="classpath:spring-mvc.xml"/></beans>

查询书籍功能

  • BookController.java
packagecom.wei.controller;importcom.wei.dao.BookMapper;importcom.wei.pojo.Books;importcom.wei.service.BookService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.RequestMapping;importjava.util.List;@Controller@RequestMapping("/book")publicclassBookController{//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")//指定一个唯一的bean对象注入privateBookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")publicStringlist(Model model){List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);return"allBook";}}
  • 首页index.jsp
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/11/28
  Time: 14:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>

    <style>
        a{
            text-decoration: none;
            color: black;
            font-size: 18px;
        }
        h1{
            width: 180px;
            height: 38px;
            margin: 100px auto;
            text-align: center;
            line-height: 38px;
            background: deeppink;
            border-radius: 5px;
        }
    </style>
</head>
<body>

<h1>
  <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h1>

</body>
</html>
  • 书籍列表页面allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/11/28
  Time: 15:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</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 clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                    <tr>
                        <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>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

添加书籍功能

  • BookController.java
packagecom.wei.controller;importcom.wei.dao.BookMapper;importcom.wei.pojo.Books;importcom.wei.service.BookService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.RequestMapping;importjava.util.List;@Controller@RequestMapping("/book")publicclassBookController{//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")//指定一个唯一的bean对象注入privateBookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")publicStringlist(Model model){List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);return"allBook";}//跳转到增加书籍页面@RequestMapping("/toAddBook")publicStringtoAddPaper(){return"addBook";}//添加书籍的请求@RequestMapping("/addBook")publicStringaddBook(Books books){System.out.println("addBook:"+ books);
        bookService.addBook(books);return"redirect:/book/allBook";//重定向到@RequestMapping("/allBook")请求}}
  • addBook.jsp添加书籍页面
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/12/1
  Time: 14:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加书籍</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</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>

        <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">
                <button type="submit" class="btn btn-primary">添加</button>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

修改书籍功能

  • BookController.java
packagecom.wei.controller;importcom.wei.dao.BookMapper;importcom.wei.pojo.Books;importcom.wei.service.BookService;importorg.apache.ibatis.annotations.Param;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importjava.util.List;@Controller@RequestMapping("/book")publicclassBookController{//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")//指定一个唯一的bean对象注入privateBookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")publicStringlist(Model model){List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);return"allBook";}//跳转到增加书籍页面@RequestMapping("/toAddBook")publicStringtoAddPaper(){return"addBook";}//添加书籍的请求@RequestMapping("/addBook")publicStringaddBook(Books books){System.out.println("addBook:"+ books);
        bookService.addBook(books);return"redirect:/book/allBook";//重定向到@RequestMapping("/allBook")请求}//跳转到修改页面@RequestMapping("/toUpdate")publicStringtoUpdatePaper(int id,Model model){Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);return"updateBook";}//修改书籍@RequestMapping("/updateBook")publicStringupdateBook(Books books){System.out.println("updateBook=>"+books);int i = bookService.updateBook(books);if(i>0){System.out.println("添加Books成功"+books);}else{System.out.println("添加Books失败");}return"redirect:/book/allBook";}}
  • updateBook.jsp修改书籍页面
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/12/3
  Time: 14:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</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>

        <form action="${pageContext.request.contextPath}/book/updateBook" method="post">

            <%--前端隐藏域:页面无法看见,默认提交到后台--%>
            <input type="hidden" name="bookID" value="${books.bookID}">

            <div class="form-group">
                <label>书籍名称:</label>
                <input type="text" name="bookName" class="form-control" value="${books.bookName}" required>
            </div>
            <div class="form-group">
                <label>书籍数量:</label>
                <input type="text" name="bookCounts" class="form-control" value="${books.bookCounts}" required>
            </div>
            <div class="form-group">
                <label>书籍描述:</label>
                <input type="text" name="detail" class="form-control" value="${books.detail}" required>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">修改</button>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

删除书籍功能

  • BookController.java
packagecom.wei.controller;importcom.wei.dao.BookMapper;importcom.wei.pojo.Books;importcom.wei.service.BookService;importorg.apache.ibatis.annotations.Param;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importjava.util.List;@Controller@RequestMapping("/book")publicclassBookController{//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")//指定一个唯一的bean对象注入privateBookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")publicStringlist(Model model){List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);return"allBook";}//跳转到增加书籍页面@RequestMapping("/toAddBook")publicStringtoAddPaper(){return"addBook";}//添加书籍的请求@RequestMapping("/addBook")publicStringaddBook(Books books){System.out.println("addBook:"+ books);
        bookService.addBook(books);return"redirect:/book/allBook";//重定向到@RequestMapping("/allBook")请求}//跳转到修改页面@RequestMapping("/toUpdate")publicStringtoUpdatePaper(int id,Model model){Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);return"updateBook";}//修改书籍@RequestMapping("/updateBook")publicStringupdateBook(Books books){System.out.println("updateBook=>"+books);int i = bookService.updateBook(books);if(i>0){System.out.println("添加Books成功"+books);}else{System.out.println("添加Books失败");}return"redirect:/book/allBook";}//删除书籍@RequestMapping("/deleteBook/{bookID}")publicStringdeleteBook(@PathVariable("bookID")int id){
        bookService.deleteBookById(id);return"redirect:/book/allBook";}}

搜索功能

  • BookMapper.java
//查询数据BooksqueryBooksByName(String bookName);
  • BookMapper.xml
<selectid="queryBooksByName"parameterType="String"resultType="Books">
    select * from ssmbuild.books where bookName like '%${bookName}%';
</select>
  • BookService.java
//查询数据BooksqueryBooksByName(String bookName);
  • BookServiceImpl.java
@OverridepublicBooksqueryBooksByName(String bookName){return bookMapper.queryBooksByName(bookName);}
  • BookController.java
//查询数据@RequestMapping("/queryBooks")publicStringqueryBooks(String queryBookName,Model model){Books books = bookService.queryBooksByName(queryBookName);System.err.println("Books:"+ books);List<Books> list =newArrayList<Books>();
    list.add(books);System.out.println("queryBookName:"+ queryBookName);if(books ==null|| queryBookName ==null){
        list = bookService.queryAllBook();
        model.addAttribute("Error","未查到书籍");}
    
    model.addAttribute("list", list);return"allBook";}
  • allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/11/28
  Time: 15:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</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 class="col-md-8">
            <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">
            <%--查询书籍--%>
            <form action="${pageContext.request.contextPath}/book/queryBooks" method="post">
                <div class="input-group mb-3">
                    <span style="color: red;font-weight: bold;line-height: 32px">${Error}</span>
                    <input type="text" name="queryBookName" class="form-control" placeholder="请输入查询书籍名称" required>
                    <div class="input-group-append">
                        <button class="btn btn-primary" type="submit">查询</button>
                    </div>
                </div>
            </form>
        </div>

    </div>

    <div class="row">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>书籍编号</th>
                    <th>书籍名称</th>
                    <th>书籍数量</th>
                    <th>书籍详细</th>
                    <td>操作</td>
                </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/toUpdate?id=${book.bookID}">修改</a>
                            &nbsp; | &nbsp;
                            <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

本文转载自: https://blog.csdn.net/weixin_62765017/article/details/128748386
版权归原作者 wei_shuo 所有, 如有侵权,请联系我们删除。

“Sprig框架集成(SSM框架) | Sping+SpringMVC+Mybatis”的评论:

还没有评论