初始SpringMVC(肆)整合篇

11.SMM整合

环境

  • IDE工具
  • Tomcat 8.5.78
  • Maven 3.8.5
  • 依赖如下
    <!-- 依赖 -->
    <dependencies>
        <!-- junit:测试包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!-- MySql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <!-- 数据库连接池:c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- jsp -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- jstl:jsp标签库 -->
        <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.9</version>
        </dependency>
        <!-- MyBaits-Spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.19</version>
        </dependency>
        <!-- Spring-JDBC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.19</version>
        </dependency>
    </dependencies>

配置解决静态资源导出问题:

    <!-- 在build配置resources,来防止资源导出失败的问题! -->
    <build>
        <resources>
            <!-- 配置文件过滤 -->
            <resource>
                <!-- 配置路径 -->
                <directory>src/main/java</directory>
                <!-- 配置过滤文件 -->
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <!-- 确认过滤 -->
                <filtering>true</filtering>
            </resource>
            <!-- 同理 -->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

创建数据库:

-- 创建数据库
CREATE DATABASE if not exists `ssmbuild`;

-- 进入数据库
USE `ssmbuild`;

-- 如果有books这张表则删除
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, '从进门到进牢');

创建文件夹(包):

 在domain(或者pojo)编写实体类:

package com.xiao.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private Integer bookID;
    private String bookName;
    private Integer bookCounts;
    private String detail;
}

在mapper编写Booksmapper接口:

package com.xiao.mapper;

import com.xiao.domain.Books;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface BookMapper {
    /**
     * 添加一本书
     */
    Integer addBook(Books book);

    /**
     * 删除一本书
     */
    Integer deleteBook(Integer id);

    /**
     * 修改一本书
     */
    Integer updateBook(Books book);

    /**
     * 查询一本书
     */
    Books queryBookByID(Integer id);

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

}

编写BooksMapper.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.xiao.mapper.BookMapper">

    <!--增加一个Book-->
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books(bookName, bookCounts, detail)
        values (#{bookName}, #{bookCounts}, #{detail})
    </insert>

    <!--根据id删除一个Book-->
    <delete id="deleteBookById" parameterType="int">
        delete
        from ssmbuild.books
        where bookID = #{bookID}
    </delete>

    <!--更新Book-->
    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName   = #{bookName},
            bookCounts = #{bookCounts},
            detail     = #{detail}
        where bookID = #{bookID}
    </update>

    <!--根据id查询,返回一个Book-->
    <select id="queryBookById" resultType="Books">
        select *
        from ssmbuild.books
        where bookID = #{bookID}
    </select>

    <!--查询全部Book-->
    <select id="queryAllBook" resultType="Books">
        SELECT *
        from ssmbuild.books
    </select>

</mapper>

编写Service接口:

package com.xiao.service;

import com.xiao.domain.Books;

import java.util.List;

public interface BookService {
    /**
     * 添加一本书
     */
    Integer addBook(Books book);

    /**
     * 删除一本书
     */
    Integer deleteBook(Integer id);

    /**
     * 修改一本书
     */
    Integer updateBook(Books book);

    /**
     * 查询一本书
     */
    Books queryBookByID(Integer id);

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

编写service接口实现类:

package com.xiao.service;

import com.xiao.domain.Books;
import com.xiao.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    //Service嗲用Mapper层
    @Autowired
    private  BookMapper bookMapper;

    //set方法方便Spring注入
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
        System.out.println(bookMapper.queryAllBook());
    }

    @Override
    public Integer addBook(Books book) {
        return bookMapper.addBook(book);
    }

    @Override
    public Integer deleteBook(Integer id) {
        return bookMapper.deleteBook(id);
    }

    @Override
    public Integer updateBook(Books book) {
        return bookMapper.updateBook(book);
    }

    @Override
    public Books queryBookByID(Integer id) {
        return bookMapper.queryBookByID(id);
    }

    @Override
    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

编写完结构如下:

创建配置文件:

 编写MyBaits配置文件:

<?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.xiao.domain"/>
    </typeAliases>
    <!-- 注册Mapper.xml -->
    <mappers>
        <mapper resource="com/xiao/mapper/BookMapper.xml"/>
    </mappers>

</configuration>

编写数据库配置文件:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=98526

编写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"
       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">

    <import resource="spring-mapper.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="springmvc-servlet.xml"/>
    
</beans>

编写spring-mapper.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">


    <!-- 1.关联数据库配置文件 -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.连接池
     dbcp:半自动化操作,不能自动去连接
     c3p0:自动化操作,自动化加载配置文件,并且可以自动设置到对象中
     druid:hirari
     -->
    <context:component-scan base-package="com.xiao.mapper"/>
    <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"/>
        <!-- 关闭连接后不自动回滚 -->
        <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"/>
        <!-- 绑定MyBaits配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

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

</beans>

编写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
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 1.扫service下的包 -->
    <context:annotation-config/>
    <context:component-scan base-package="com.xiao.service"/>


    <!-- 2.将我们所有的业务类注入到Spring可以通过配置或者注解实现 -->

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

</beans>

编写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>

编写springmvc-servlet.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">

    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven />
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <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>

    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.xiao.controller" />

</beans>

最终目录结构:

编写页面实现增删改查:

  控制器

package com.xiao.controller;

import com.xiao.domain.Books;
import com.xiao.service.BookService;
import org.apache.ibatis.annotations.Param;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping("/allBook")
    public String allBook(Model model) {
        model.addAttribute("msg", bookService.queryAllBook());
        return "book";
    }

    @GetMapping("/add")
    public String add() {
        return "add";
    }

    //增加数据
    @PostMapping("/add")
    public String add(Books book) {
        bookService.addBook(book);
        //重定向到查询页面
        return "redirect:/book/allBook";
    }

    //跳转修改页面
    @GetMapping("/update/{bookID}")
    public String update(@PathVariable("bookID") Integer bookID, Model model) {
        Books books = bookService.queryBookByID(bookID);
        model.addAttribute("book", books);
        return "update";
    }

    //修改页面数据
    @PostMapping("/update")
    public String update(Books book) {
        bookService.updateBook(book);
        //重定向到查询页面
        return "redirect:/book/allBook";
    }

    //删除数据
    @RequestMapping("/delete/{bookID}")
    public String delete(@PathVariable("bookID") Integer bookID) {
        bookService.deleteBook(bookID);
        return "redirect:/book/allBook";
    }

    //查询书籍
    @PostMapping("/queryBook")
    public String queryBook(@Param("queryBookName") String queryBookName,Model model){
        System.out.println(queryBookName);
        List<Books> books = bookService.queryBook(queryBookName);
        model.addAttribute("msg", books);
        return "book";
    }
}

 编写主页面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://maxcdn.bootstrapcdn.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 class="h1">
                    <small>书籍列表---显示所有书籍</small>
                </h1>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4 column right">
                <a class="btn btn-primary right" href="${pageContext.request.contextPath}/book/add">新增书籍</a>
            </div>

            <div class="col-md-4 column">
                <%-- 查询书籍 --%>
                <form action="${pageContext.request.contextPath}/book/queryBook" method="post">
                    <label>
                        <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍名称">
                    </label>
                    <input type="submit" class="btn btn-primary right" value="查询">
                </form>
            </div>
        </div>
    </div>

    <%-- row clearfix:清除浮动 --%>
    <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="${msg}">
                    <tr>
                        <td>${book.bookID}</td>
                        <td>${book.bookName}</td>
                        <td>${book.bookCounts}</td>
                        <td>${book.detail}</td>
                        <td><a href="${pageContext.request.contextPath}/book/delete/${book.bookID}"
                               class="btn btn-danger right ">删除</a> &nbsp;&nbsp; <a
                                href="${pageContext.request.contextPath}/book/update/${book.bookID}"
                                class="btn btn-danger right">修改</a></td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

</div>


</body>
</html>

编写增加页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://maxcdn.bootstrapcdn.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 class="h1">
                    <small>新增书籍</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/add" method="post">
        <div class="form-group">
            <label for="name">书籍名称:</label>
            <input type="text" class="form-control" id="name" name="bookName">
        </div>
        <div class="form-group">
            <label for="counts">书籍数量:</label>
            <input type="text" class="form-control" id="counts" name="bookCounts">
        </div>
        <div class="form-group">
            <label for="detail">书籍描述:</label>
            <input type="text" class="form-control" id="detail" name="detail">
        </div>

        <div class="form-group">
            <label for="submit"></label>
            <input type="submit" class="form-control" id="submit" value="新增书籍">
        </div>
    </form>
</div>

</body>
</html>

编写修改页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://maxcdn.bootstrapcdn.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 class="h1">
                    <small>修改书籍</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/update" method="post">
        <input type="hidden" class="form-control"  id="id" name="bookID" value="${book.bookID}">

        <div class="form-group">
            <label for="name">书籍名称:</label>
            <input type="text" class="form-control" id="name" name="bookName" value="${book.bookName}">
        </div>
        <div class="form-group">
            <label for="counts">书籍数量:</label>
            <input type="text" class="form-control" id="counts" name="bookCounts" value="${book.bookCounts}">
        </div>
        <div class="form-group">
            <label for="detail">书籍描述:</label>
            <input type="text" class="form-control" id="detail" name="detail" value="${book.detail}">
        </div>

        <div class="form-group">
            <label for="submit"></label>
            <input type="submit" class="form-control" id="submit" value="修改书籍">
        </div>
    </form>
</div>

</body>
</html>

效果:

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

123小步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值