狂神SSM整合项目

首先进行配置

在idea中新建maven项目,然后在pom文件中导入所有需要的依赖

<?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>org.example</groupId>
    <artifactId>kuang-SSM-Build</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.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.3.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.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>

导入web框架支持

然后配置一下tomcat,切记把所有的jar包导入一下

再然后狂所有的jar包导入一下,不然会报错

这个是用到的sql文件,新建查询运行至即可,如果不成功的话,可以尝试把 DROP TABLE IF EXISTS `books`;这句删掉

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

接下来我们吧最基本的包结构搭建好

 我们开始写mybatis的配置文件了

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

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- 配置数据源,交给Spring去做-->
    <typeAliases>
        <package name="pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="mapper.BookMapper"></mapper>
    </mappers>



</configuration>

这里需要注意的是,一定要把mapper在这里面注册一下,不然会报错找不到mapper了

 <mappers>
        <mapper class="mapper.BookMapper"></mapper>
    </mappers>

 注意配置的时候一定要按照这个顺序来进行配置(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)".

接下来我们写一下database.properties

jdbc.driver=com.mysql.jdbc.Driver
# 如果使用的是MySql8.0+,增加一个时区的配置
# serverTimezone=GMT%2B8 表示中国的时区 北京时间
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&Unicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=yyh416333

接下来使用idea链接一下数据库,

接下来把底层的活干好了,开始使用lombook插件写一下实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books implements Serializable {

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

编写bookMapper的接口

public interface BookMapper {
    //增加一本书

    int addBook(Books books);

    //删除一本书

    int deleteBookById(@Param("bookId") int id);

    //修改一本书

    int updateBook(Books books);

    //查询一本书

    Books queryBookById(int id);

    //查询全部的书

    List<Books> queryAllBook();

    //通过书名查询图书

    List<Books> queryBookByName(@Param("bookName") String bookName);
}

接下来写mapper.xml,也就是写一些sql语句,相比较狂神的呢我新增了一个按照书名查询的模糊查询

这里补充一下#和$的区别

1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id".
  
2. $将传入的数据直接显示生成在sql中。如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id,  如果传入的值是id,则解析成的sql为order by id.
  
3. #方式能够很大程度防止sql注入。
  
4.$方式无法防止Sql注入。

5.$方式一般用于传入数据库对象,例如传入表名.
  
6.一般能用#的就别用$.

MyBatis排序时使用order by 动态参数时需要注意,用$而不是#

字符串替换
默认情况下,使用#{}格式的语法会导致MyBatis创建预处理语句属性并以它为背景设置安全的值(比如?)。这样做很安全,很迅速也是首选做法,有时你只是想直接在SQL语句中插入一个不改变的字符串。比如,像ORDER BY,你可以这样来使用:
ORDER BY ${columnName}
这里MyBatis不会修改或转义字符串。

重要:接受从用户输出的内容并提供给语句中不变的字符串,这样做是不安全的。这会导致潜在的SQL注入攻击,因此你不应该允许用户输入这些字段,或者通常自行转义并检查。

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

<mapper namespace="mapper.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books(bookName,bookCounts,detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID = #{bookId}
    </delete>

    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set   bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookID};
    </update>

    <select id="queryBookById" resultType="Books">
        select * from ssmbuild.books where bookID = #{bookId}
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books
    </select>

    <select id="queryBookByName" resultType="Books">
        select * from books where bookName like concat('%',#{bookName},'%')
    </select>
</mapper>

一般模糊查询呢就使用 like concat()就可以了

开始写service层的接口和实现类

public interface BookService {
    //增加一本书
    int addBook(Books books);

    //删除一本书
    int deleteBookById(int id);

    //修改一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(int id);

    //查询全部的书
    List<Books> queryAllBook();

    List<Books> queryBookByName(String bookName);
}
public class BookServiceImpl implements BookService{


    //serivce调用dao层,组合Dao
    @Autowired
    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 updateBook(Books books) {
        return bookMapper.updateBook(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-dao.xml   还是狂神老师的那句话,spring呢就是一个大容器,我们吧所有的东西都交给了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">

    <!-- 1. 关联数据库配置文件-->
    <context:property-placeholder location="classpath:database.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"></property>
        <!-- 绑定MyBatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    <!-- 配置dao接口扫描包,动态的实现了Dao接口可以注入到spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 要扫描的dao包-->
        <property name="basePackage" value="mapper"/>
    </bean>



</beans>

按照dao-service-mvc的顺序来配置,接下来是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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--解决service中识别不到bookMapper 第一种 关联service和dao-->
<!--    <import resource="spring-dao.xml"/>-->
    <!--第二种 将所有的配置到application.xml中即可 -->
    <!-- 在BookServiceImpl中对DAO层中的bookMapper进行注解autowired自动装配-->
    <!-- 扫描service下的包-->
    <context:component-scan base-package="service"/>

    <!-- 2.将我们的所有业务类注入到spring,可以通过配置或者注解实现-->
    <bean id="BookServiceImpl" class="service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!-- 声明式事务配置-->
    <bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 4.aop事务支持!-->
</beans>

然后开始配置'MVC 首先配置一下web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </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>

以及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: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">

    <!-- 1. 注解驱动-->
    <mvc:annotation-driven/>
    <!-- 2. 静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!-- 3. 扫描宝: controller-->
    <context:component-scan base-package="controller"/>
    <!-- 4. 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

这里将所有的配置文件都import到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="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>

</beans>

这时候我们基本的准备工作就完成了,然后开始进行一些有难度的事情了,就是编写controller层以及写前端页面了!。本次前端页面会使用到bootstrap,所以需要在写前端页面的时候,引入这句话。

<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

开始编写BookController类

@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";
  }
}

这里写的是一个查询全部书籍的方法,通过调用bookService的queryAllBook方法然后把查到的值放到Listl里面并把它添加到model对象中,他可以在jsp被取出来并进行渲染。

然后开始写前端页面首页index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
    <style>
      a{
        text-decoration: none;
        color: black;
        font-size:19px;
      }
      h3{
        width:180px;
        height:38px;
        margin: 100px auto;
        text-align: center;
        line-height: 38px;
        background: deepskyblue;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
  <h3>
    <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
  </h3>
  </body>
</html>

接下来要注意到的是,我们在之前配置spring-MVC的时候,已经写好了视图解析器

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

就是这里,所以我们需要在WEB-INF下建立一个名字为jsp的文件夹,prefix的意思是前缀,suffix的意思是后缀,所以我们跳转的时候不用再写.jsp这种了。

接下来写我们的allBook.jsp界面,这个界面呢就是我们的主页面,展示了全部书籍而且我们进行增删改查也是在这个页面中进行操作。

注意一下,这里的修改跟提交的时候跳转的请求修改是传统的?参数,而删除请求采用了restful风格

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>书籍展示页面</title>
    <!-- 使用BootStrap 美化界面-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/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="row">
            <div class="col-md-6 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>

                    <%-- 查询书籍--%>
                <form action="${pageContext.request.contextPath}/book/queryBook" method="post" >
                    <div class="col-md-4 column">
                    <input  type="text" style="float: left" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍名称">
                    </div>
                    <div class="col-md-1 column">
                    <input  type="submit"  value="查询" class="btn btn-primary">
                    </div>
                    <div class="col-md-1 column">
                        <span style="color:red;font-weight: bold;font-size:22px;float:right">${error}</span>
                    </div>
                </form>
        </div>

    </div>
    <h1></h1>
    <h1></h1>
    <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>
                <!-- 书籍从数据库中查询出来,从这个list中遍历出来,foreach-->
                <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>
</div>

</body>
</html>

接下来写第二个方法了,添加书籍

@RequestMapping("/toAddBook")
public String toAddPaper() {
   return "addBook";
}

@RequestMapping("/addBook")
public String addPaper(Books books) {
   System.out.println(books);
   bookService.addBook(books);
   return "redirect:/book/allBook";
}

这里呢在添加完成后需要跳转到allbook页面上

这里呢需要重定向,如果使用JSON的话可以动态请求响应,局部刷新,就不用这么麻烦了,但是我JSON只能看懂,不会写QAQ哈哈哈哈就用这个吧,回头我把JSON实现的搬上来。

那下面就开始写addBook.jsp了,这个页面用来让用户进行添加书籍

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新增图书</title>


</head>
<body>

<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="bookname">书籍名称</label>
        <input type="text" class="form-control" name="bookName" id="bookname" required>
    </div>
    <div class="form-group">
        <label>书籍数量</label>
        <input type="text" name="bookCounts" class="form-control" required>
    </div>
    <div class="form-group">
        <label>书籍描述</label>
        <input type="text" name="detail" class="form-control" required>
    </div>
    <div class="form-group">
        <input type="submit" class="form-control" value="添加">
    </div>
</form>


</body>
</html>

接下来完成修改的方法

@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(Books books){
        System.out.println("updateBook=>"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

然后是前端展示的updateBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<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">
    <div class="form-group">
        <label for="bookname">书籍名称</label>
        <input type="hidden" name="bookID" value="${QBook.bookID}">
        <input type="text" class="form-control" name="bookName" id="bookname" value="${QBook.bookName}" required>
    </div>
    <div class="form-group">
        <label>书籍数量</label>
        <input type="text" name="bookCounts" class="form-control" value="${QBook.bookCounts}" required>
    </div>
    <div class="form-group">
        <label>书籍描述</label>
        <input type="text" name="detail" class="form-control" value="${QBook.detail}" required>
    </div>
    <div class="form-group">
        <input type="submit" class="form-control" value="添加">
    </div>
</form>


</body>
</html>

这里呢其实是有一些绕弯的,首先用户在allBook.jsp上点击了修改按钮,然后发起了toUpdateBook的请求,其实这个说白了就是查询,得把要修改的图书信息查出来在updateBook.jsp中展示出来,所以呢这里是直接转发道了updateBook.jsp然后用户进行有选择的修改,修改玩以后点了了修改按钮这时候进行了updateBook的请求,(注意,在updateBook中,id会隐藏起来,其实也会一并查出来,这时候进行updateBook请求其实是带着id传走的)这时候才会真正的进行修改,修改完成后返回到allBook界面。

然后是删除,这个比较简单,删除完成后直接刷新一下继续回到了原来的allBook界面了

    @RequestMapping("/deleteBook/{bookid}")
    public String deleteBook(@PathVariable("bookid") int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

接下来就进行按照书的名称进行查询了

    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){


        List<Books> bookslist = bookService.queryBookByName(queryBookName);

        if(bookslist==null){
                bookslist = bookService.queryAllBook();
                model.addAttribute("error","未查到");
        }
        model.addAttribute("list",bookslist);
        return "allBook";
    }

这个其实呢有个小设计,就是在没有查到时候时候,通过model对象给前端返回一个没查到的提示,在allBook界面点击查询,执行以后继续返回到allBook界面

最后呢聊聊这个转发跟重定向

请求转发是服务器内部的跳转,浏览器的地址栏不会发生变化。从一个页面到另一个页面的跳转还是同一个请求,也即是只有一个请求响应。可以通过request域来传递对象。
重定向:是浏览器自动发起对跳转目标的请求,浏览器的地址栏会发生变化。从一个页面到另一个页面的跳转是不同的请求,也即是有两个或两个以上的不同的请求的响应。无法通过request域来传递对象。

而在这个项目呢,为什么有时候用转发,有时候需要重定向呢,通俗来说增删改需要重定向,查不需要,为什么呢,因为增删改都会涉及到跟数据库的一些操作,我们需要操作完成以后,将请求重定向到@RequestMapping("/allBook")中(相当于再进行一次查询),而查询呢我们只需要将查询到的数据保存在model对象中,直接转发到allBook页面中就可以显示出来了

 还有最关键的需要说明的是,其实转发呢是会通过视图解析器的,视图解析器会自动的给他加上前缀后缀变成一个jsp页面,而重定向不是。

举例就是return "redirect:/book/allBook"重定向到我们的@RequestMapping("/allBook")请求

而return "allBook"就是转发到了allBook.jsp中了

还有就是转发的时候一般需要用Model对象来保存对象啊数据啊这些的,这样到了前端页面会自动识别到,而重定向就是执行完增删改操作,重定向到另一个请求,那个请求再查询具体改变之后的值。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值