天天看点

整合SSM框架-简易图书管理系统

整合SSM框架-简易图书管理系统

1、创建数据库

CREATE DATABASE ssmbuild;
USE ssmbuild;
CREATE TABLE `books`(
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT "书id",
`bookName` VARCHAR(100) NOT NULL COMMENT "书名",
`bookCounts` INT 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,"从入门到入狱");
           

2、导入依赖以及解决静态资源导出问题

<!--依赖:junit、数据库驱动、连接池、servlet、jsp、mybatis、mybatis-spring、spring、lombok-->

    <dependencies>
        <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.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <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.3.9</version>
        </dependency>
                <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</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>
           

3、创建项目结构

dao、service、pojo、controller

4、配置文件

  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:springmvc-servlet.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>

</beans>
           
  • mybatis-config.xml
<?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.lengzher.pojo"/>
    </typeAliases>

        <mappers>
            <mapper class="com.lengzher.dao.BookMapper"/>
        </mappers>
</configuration>
           

5、创建实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
    private int id;
    private String bookName;
    private int bookCount;
    private String detail;
}
           

6、持久层-Mybatis

  • 接口
public interface BooksMapper {
    //查询一本书
    Books queryBookById(@Param("bookID") int id);

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

    //添加一本书
    int addBook(Books books);

    //修改
    int updateBook(Books books);

    //删除
    int delBook(@Param("bookID") int id);

}
           
  • 接口对应的Mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lengzher.dao.BooksMapper">
    <select id="queryBookById" parameterType="int" resultType="Books">
        select * from books where BookID = #{BookID}
    </select>
    <select id="queryBooks" resultType="Books">
        select * from books
    </select>
    <insert id="addBook" parameterType="Books">
        insert into books (bookName, bookCounts, detail) values
        (#{bookName},#{bookCounts},#{detail})
    </insert>
    <update id="updateBook" parameterType="Books">
        update books set bookName=(#{bookName}),bookCounts=(#{bookCounts}),detail=(#{detail})
    </update>
    <delete id="delBook" parameterType="int">
        delete from books where BookID = #{BookID}
    </delete>
</mapper>
           
  • 在mybatis-config.xml中注册Mapper
<mappers>
    <mapper class="com.lengzher.dao.BooksMapper"/>
</mappers>
           

7、业务层

  • 接口
public interface BookService {
    //查询一本书
    Books queryBookById( int id);

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

    //添加一本书
    int addBook(Books books);

    //修改
    int updateBook(Books books);

    //删除
    int delBook( int id);
}
           
  • 接口实现类
public class BookServiceImpl implements BookService{

    //Service层调用Dao层
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper){
        this.bookMapper = bookMapper;
    }

    public Books queryBookById(int id) {
        return this.bookMapper.queryBookById(id);
    }

    public List<Books> queryBooks() {
        return this.bookMapper.queryBooks();
    }

    public int addBook(Books books) {
        return this.bookMapper.addBook(books);
    }

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

    public int delBook(int id) {
        return this.bookMapper.delBook(id);
    }
}
           

8、Spring框架使用

  • spring-dao.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/beans/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"/>
        <!--绑定mybatis的配置文件-->
        <property name="configLocation" value="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.lengzher.dao"/>
    </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/beans/context.xsd
        ">

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

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

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

</beans>
           

9、SpringMVC框架使用

  • 配置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">

    <!--DispatchServlet-->
    <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:springmvc-servlet.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>
           
  • 配置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: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/mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

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

Tips:框架已经整合完了,记得在applicationContext.xml文件中导入其他三个配置文件:

<import resource="classpath:springmvc-servlet.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
           

10、查询功能实现

  • 控制层代码
@Controller
@RequestMapping("/book")
public class BookController {
    //controller层调用service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部书籍,并返回书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> books = bookService.queryBooks();

        model.addAttribute("list",books);

        return "allBook";
    }
}
           
  • 首页index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
    <style>
      *{margin:0; padding:0}
      body{
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      a{
        padding:10px;
        text-decoration: none;
        color: black;
        font-size: 18px;
        border-radius: 5px;
        box-shadow: 2px 2px 5px 5px black;
      }
    </style>

  </head>
    <a href="${pageContext.request.contextPath}book/allBook" target="_blank" rel="external nofollow"  style="align-content: center">跳转到书籍展示页面</a>
  </body>
</html>
           
  • 书籍展示页面allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 17700
  Date: 2021/9/16
  Time: 15:39
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示</title>

    <%--Bootsrap美化界面--%>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" rel="stylesheet">

</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-4 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表</small>
                </h1>
            </div>
        </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>
</body>
</html>
           

11、添加书籍

  • 在书籍展示页面添加:添加书籍按钮
<a href="${pageContext.request.contextPath}/book/toAddPager" target="_blank" rel="external nofollow"  style="float: right; font-size: 20px;text-decoration: underline;color:gray">
    <h5>新增书籍</h5>
</a>
           
  • 控制层实现跳转
//跳转到添加书籍页面
@RequestMapping("/toAddPager")
public String goAddBook() {
return "addBook";
}
           
  • 创建添加书籍页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>新增书籍</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" rel="stylesheet">
</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">
        书籍名称:<input type="text" name="bookName"><br><br><br>
        书籍数量:<input type="text" name="bookCounts"><br><br><br>
        书籍详情:<input type="text" name="detail"><br><br><br>
        <input type="submit" value="添加">
    </form>
</div>
           
  • 控制层添加书籍
//添加书籍页面
@RequestMapping("/addBook")
public String addBook(Books books) {
    System.out.println("addBook=》"+books);
    bookService.addBook(books);
    return "redirect:/book/allBook";//重定向到首页
}
           

12、删除书籍

//删除书籍
@RequestMapping("/delBook/{bookId}")
public String delBook(@PathVariable("bookId") int id){
    bookService.delBook(id);
    return "redirect:/book/allBook";
}
           

13、搜索功能

  • 前端添加搜索框
<form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="text-decoration: underline;color:gray;height: 10px ">
              <input type="submit" value="查询">
                <input type="text" name="queryBookName" placeholder="请输入要查询的书籍">
            </form>
           
  • 持久层接口
//通过书名查询书籍
    List<Books> queryBookByName(String bookName);
           
  • 持久层接口实现Mapper
<select id="queryBookByName" resultType="Books">
        select * from books where bookName like "%"#{bookName}"%";
    </select>
           
  • 业务层接口
//通过书名查询书籍
    List<Books> queryBookByName(String bookName);
           
  • 业务层接口实现类
public List<Books> queryBookByName(String bookName) {
        return this.bookMapper.queryBookByName(bookName);
    }
           
  • 控制层
//搜索书籍
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        List<Books> list = bookService.queryBookByName(queryBookName);
        model.addAttribute("list",list);
        return "allBook";
    }