整合SSM框架:书籍管理系统

环境要求
  • IDEA
  • MySQL 5.0以上版本
  • tomcat 9
  • maven 3.6
数据库环境

建立一个存放书籍信息的数据库表

CREATE DATABASE `ssm`;

CREATE TABLE `books`(
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(30) 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',5,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',12,'从进门到坐牢');
基本环境搭建

1,新建空的maven项目,添加web支持。
2,导入相关依赖。

 <dependencies>
       <!--    servlet依赖-->
       <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>javax.servlet-api</artifactId>
           <version>4.0.1</version>
           <scope>compile</scope>
       </dependency>
       <!--jsp依赖-->
       <dependency>
           <groupId>javax.servlet.jsp</groupId>
           <artifactId>javax.servlet.jsp-api</artifactId>
           <version>2.3.3</version>
           <scope>provided</scope>
       </dependency>

       <!-- jstl表达式的依赖 -->
       <dependency>
           <groupId>javax.servlet.jsp.jstl</groupId>
           <artifactId>jstl-api</artifactId>
           <version>1.2</version>
       </dependency>

       <!-- standard标签库 -->
       <dependency>
           <groupId>taglibs</groupId>
           <artifactId>standard</artifactId>
           <version>1.1.2</version>
       </dependency>

       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.12</version>
           <scope>test</scope>
       </dependency>
       <dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
           <version>1.18.20</version>
       </dependency>

       <!-- mysql驱动-->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.25</version>
       </dependency>
       <!-- mybatis驱动-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.7</version>
       </dependency>
<!--       数据库连接池-->
       <dependency>
           <groupId>com.mchange</groupId>
           <artifactId>c3p0</artifactId>
           <version>0.9.5.2</version>
       </dependency>
       <!--    Spring 依赖-->
       <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-webmvc</artifactId>
           <version>5.3.9</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>5.1.3.RELEASE</version>
       </dependency>
       <!--        mybatis-spring-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis-spring</artifactId>
           <version>2.0.5</version>
       </dependency>
   </dependencies>

3,资源过滤设置

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

4,建立基本结构和配置框架。
整合SSM框架:书籍管理系统

Mybatis层编写

1,数据库配置文件database.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSl=true&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

2,idea关联数据库
3,编写myBatis的核心配置文件

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>

<!--    配置数据源,这里交给Spring去做-->
    
    <typeAliases>
        <package name="com.tt.pojo"/>
    </typeAliases>
    
</configuration>

4,编写数据库对应的实体类,com.tt.pojo.Books(这里使用了LomBok插件)

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

5,编写Dao层接口BookMapper

package com.tt.dao;

import com.tt.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {
    //增加一本书
    int addBook(Books books);
    //删除一本书
    int deleteBookById(@Param("bookId") int id);
    //查询一本书
    Books queryBooksById(@Param("bookId") int id);
    //更新一本书
    int updateBook(Books books);
    //查询全部书籍
    List<Books> queryAllBooks();
    //根据书名查询书籍
    Books queryBookByName(@Param("bookName") String bookName);
}

6,编写对应的Mapper.xml映射文件

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--mybatis核心配置文件-->
<mapper namespace="com.tt.dao.BookMapper">

<insert id="addBook" parameterType="Books">
    insert into ssm.books(bookName,bookCounts,detail)
        value (#{bookName},#{bookCounts},#{detail})
</insert>

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

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

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

    <select id="queryAllBooks" resultType="Books">
        select * from ssm.books
    </select>

    <select id="queryBookByName" resultType="Books">
        select * from ssm.books where bookName=#{bookName}
    </select>


</mapper>

7,编写service业务层接口

package com.tt.service;

import com.tt.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookService {
    //增加一本书
    int addBook(Books books);
    //删除一本书
    int deleteBookById(int id);
    //查询一本书
    Books queryBooksById(int id);
    //更新一本书
    int updateBook(Books books);
    //查询全部书籍
    List<Books> queryAllBooks();
    //根据书名查询书籍
    Books queryBookByName( String bookName);
}

8,业务层接口实现类

package com.tt.service;

import com.tt.dao.BookMapper;
import com.tt.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService{

    //service调用dao层

    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 Books queryBooksById(int id) {
        return bookMapper.queryBooksById(id);
    }

    @Override
    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

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

    @Override
    public Books queryBookByName(String bookName) {
        return bookMapper.queryBookByName(bookName);
    }
}

到此,底层操作编写完毕

Spring层

1,配置spring整合mybatis;这里数据源用c3p0连接池。
2,编写spring整合mybatis的配置文件:spring-dao.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">


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


<!--    数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
<!--        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>

<!--    sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

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

3,spring整合service spring-service.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">


<!--    1,    扫描service下的包-->
    <context:component-scan base-package="com.tt.service"/>

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

<!--  3,  声明式事务管理  -->

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

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

spring层到此结束,它是一个容器,可以整合多个配置文件

springMVC层

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

2,spring-mvc.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://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">

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

3,spring配置整合文件:applicationContext.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    将dao和service关联起来-->
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

配置文件,基本结束

Controller和视图层编写

1,BookController类编写,

package com.tt.controller;


import com.tt.pojo.Books;
import com.tt.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.RequestMapping;

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.queryAllBooks();
        model.addAttribute("list",list);
        return "allBook";
    }

    //跳转到新增书籍页面
    @RequestMapping("/toAddPage")
    public String toAddPage(){
        return "addBook";
    }

    //添加书籍功能实现
    @RequestMapping("/addBook")
    public String addBook(Books books){
     bookService.addBook(books);
     return "redirect:/book/allBook";
    }

    //跳转到修改书籍页面
    @RequestMapping("/updatePage")
    public String toUpdatePage(int id,Model model){
        Books books = bookService.queryBooksById(id);
        model.addAttribute("QBooks",books);
        return "updateBook";
    }

    //修改书籍功能实现
    @RequestMapping("updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    //删除书籍功能实现
    @RequestMapping("/deleteBook")
    public String deleteBook(int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    //查询书籍
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<>();
        list.add(books);
        if(books==null){
            list=bookService.queryAllBooks();
            model.addAttribute("error","未查询到该书籍");
        }
        model.addAttribute("list",list);
        return "allBook";
    }
}

2,首页视图,index.jsp


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

3,全部书籍页面,allBook.jsp

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

<%--    bootstrop美化界面--%>

    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body{
            background-image: linear-gradient(to top, #ebbba7 0%, #cfc7f8 100%);
        }
        #add{
            position: absolute;
            left: 400px;
            top: 100px;
            width: 80px;
            height: 25px;
            background: #369696;
            text-align: center;
            text-decoration: none;
            border-radius: 3px;
            line-height: 25px;
            color: aliceblue;
        }
        #Cx{
            width: 300px;
            margin-left: 865px;
        }
        #btn_Cx{
            margin-left: 1120px;
            margin-top: 10px;
            background: #4bd2d2;
            border-radius: 3px;
        }
        #Tx{
            color: red;
            font-weight: bold;
            margin-left: 960px;
            position: absolute;
            top: 145px;
            font-size: 16px;
        }
    </style>

</head>
<body>

<div>
    <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-4 column">
                    <a id="add" href="${pageContext.request.contextPath}/book/toAddPage">新增书籍</a>
                </div>
                <div>
                    <form action="${pageContext.request.contextPath}/book/queryBook" method="post">
                        <input id="Cx" type="text" class="form-control" name="queryBookName" placeholder="请输入要查询的书名">
                        <span id="Tx">${error}</span>
                        <input id="btn_Cx" type="submit" value="查询">
                    </form>
                </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>
                        <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/updatePage?id=${book.bookID}">修改</a>
                                 &nbsp; | &nbsp;
                                 <a href="${pageContext.request.contextPath}/book/deleteBook?id=${book.bookID}">删除</a>
                             </td>
                         </tr>
                      </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

</body>
</html>

整合SSM框架:书籍管理系统

4,添加书籍页面,addBook.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">
    <style>
        body{
            background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增数据</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        <div class="form-group">
            <lable>书籍名称</lable>
            <input type="text" class="form-control" name="bookName" required>
        </div>
        <div class="form-group">
            <lable>书籍数量</lable>
            <input type="text" class="form-control" name="bookCounts" required>
        </div>
        <div class="form-group">
            <lable>书籍描述</lable>
            <input type="text" class="form-control" name="detail" required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="添加">
        </div>
    </form>
</div>
</body>
</html>

整合SSM框架:书籍管理系统
5,修改书籍界面 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">
    <style>
        body{
            background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);

        }
    </style>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>修改数据</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <input type="hidden" name="bookID" value="${QBooks.bookID}">
        <div class="form-group">
            <lable>书籍名称</lable>
            <input type="text" class="form-control" name="bookName" value="${QBooks.bookName}" required>
        </div>
        <div class="form-group">
            <lable>书籍数量</lable>
            <input type="text" class="form-control" name="bookCounts" value="${QBooks.bookCounts}" required>
        </div>
        <div class="form-group">
            <lable>书籍描述</lable>
            <input type="text" class="form-control" name="detail" value="${QBooks.detail}" required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="确认修改">
        </div>
    </form>
</div>
</body>
</html>

整合SSM框架:书籍管理系统

上一篇:Vue3 #2


下一篇:洛谷p2895