SSM整合之图书管理系统

创建项目开发环境

创建maven项目,选择webapp骨架。
是是是是是是是
解决创建项目过慢的问题,在创建web项目时加入该键值对。
解决创建项目过慢的问题

导入依赖

<dependencies>
    <!--  junit测试  -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>

    <!--  数据库链接驱动  -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- 数据库连接池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.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>

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

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.10</version>
<!--      <scope>provided</scope>-->
    </dependency>
  </dependencies>

创建Books图书实体类

package com.zgh.pojo;

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

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {

    private String bookName;
    private Integer bookCounts;
    private String detail;

}

创建IBookMapper接口

package com.zgh.mapper;

import com.zgh.pojo.Books;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
//实现图书的增删改查
public interface IBookMapper {

    //增加图书
    int InsertBook(Books books);

    //通过书的ID删除图书
    int DeleteBook(@Param("bookId") int bookId);

    //更改图书信息
    int UpdateBook(Books books);

    //查询所有图书
    List<Books> FindAll();

    //通过id查询图书
    Books FindBookById(@Param("bookId") int bookId);

    Books findBookByName(@Param("bookName") String bookName);
}
}

IBookMapper的映射文件

<?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.zgh.mapper.IBookMapper">
    <insert id="InsertBook" parameterType="books">
        insert into books(bookName, bookCounts, detail)
        value(#{bookName},#{bookCounts},#{detail})
    </insert>

    <delete id="DeleteBook">
        delete from books where bookID = #{bookId}
    </delete>
    <update id="UpdateBook" parameterType="Books">
        update
            books
        set
            bookName=#{bookName},
            bookCounts=#{bookCounts},
            detail=#{detail}
        where bookID=#{bookID}
    </update>

    <select id="FindAll" resultType="Books">
        select * from books
    </select>

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

    <select id="findBookByName" resultType="books">
        select * from books where bookName=#{bookName}
    </select>
</mapper>

创建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>

    <typeAliases>
        <package name="com.zgh.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/zgh/mapper/BookMapper.xml"/>
        <!--        <package name="com.zgh.mapper"/>-->
    </mappers>
</configuration>

整合mybatis层

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

    <!--  整合mybatis  -->

    <context:property-placeholder location="classpath:database.properties"/>

    <context:component-scan base-package="com.zgh.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}"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>
<!--        <property name="mapperLocations" value="classpath:mybatis.xml"/>-->
    </bean>

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

整合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"
       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">

    <context:component-scan base-package="com.zgh.service"/>

    <bean id="bookService" class="com.zgh.service.BookServiceImp">
        <property name="iBookMapper" ref="IBookMapper"/>
    </bean>

    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</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>servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--  要绑定的配置文件  -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring.xml</param-value>
    </init-param>
    <!--  和servlet一并启动  -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--  配置乱码过滤  -->
  <filter>
    <filter-name>Chinese</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
    <!--  encoding是CharacterEncodingFilter内部的参数 -->
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
  </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Chinese</filter-name>
    <!--  只有/的话页面的乱码是无法解决的 -->
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- session -->
  <session-config>
  <!--  15分钟  -->
    <session-timeout>15</session-timeout>
  </session-config>
</web-app>

spring-mvc

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


    <!-- 配置注解扫描-->
    <mvc:annotation-driven/>

    <!-- 静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 配置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 扫描controller层的注解-->
   <context:component-scan base-package="com.zgh.controller"/>
</beans>

编写Controller控制层代码

package com.zgh.controller;

import com.zgh.pojo.Books;
import com.zgh.service.BookServiceImp;
import com.zgh.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

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

    @Autowired
    private BookServiceImp bookService;

    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> books = bookService.FindAll();
        model.addAttribute("list",books);
        for (Books book : books) {
            System.out.println(book);
        }
        return "allBook";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model){
        if(password.equals("123456")){
            return "forward:/book/allBook";
        }else {
            return "forward:/index.jsp";
        }
    }
    
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addPaper(Books books){
        System.out.println("addBook--->"+books);
        int i = bookService.InsertBook(books);
        System.out.println("iiii--->"+i);
//        return "allBook";
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdatePaper(Model model,int bookID) {
        Books books = bookService.FindBookById(bookID);
        model.addAttribute("uBook",books);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String pdatePaper(Books books) {
        bookService.UpdateBook(books);
        return "redirect:/book/allBook";

    }

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

    @RequestMapping("/queryByName")
    public String queryByName(String queryBookName,Model model) {
        System.out.println("bookName :"+queryBookName);
        Books books = bookService.findBookByName(queryBookName);
        System.out.println(books);
        List<Books> list = new ArrayList<Books>();
        list.add(books);
        model.addAttribute("list",list);
//        return "redirect:/book/allBook";
        return "allBook";
    }
}
}

前台界面

查询所有

<%@ 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" 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>


    <div class="row">
        <div class="col-md-4 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>

        <div class="col-md-4 column">
            <form action="${pageContext.request.contextPath}/book/queryByName" method="post" style="float: right">
                <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的数据名字">
                <input type="submit" value="查询" class="btn btn-primary">
            </form>
        </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="${requestScope.get('list')}">
                    <tr>
                        <td>${book.getBookID()}</td>
                        <td>${book.getBookName()}</td>
                        <td>${book.getBookCounts()}</td>
                        <td>${book.getDetail()}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook?bookID=${book.getBookID()}">修改</a>
                            &nbsp; | &nbsp;
                            <a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>

增加图书界面

<%--
  Created by IntelliJ IDEA.
  User: smile
  Date: 2020/5/7
  Time: 15:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新增书籍</title>
</head>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<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>
</body>
</html>

修改图书

<%--
  Created by IntelliJ IDEA.
  User: smile
  Date: 2020/5/7
  Time: 15:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍</title>
</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="${uBook.bookID}">
        书籍名称:<input type="text" name="bookName" value="${uBook.bookName}"><br><br><br>
        书籍数量:<input type="text" name="bookCounts" value="${uBook.bookCounts}"><br><br><br>
        书籍详情:<input type="text" name="detail" value="${uBook.detail}"><br><br><br>
        <input type="submit" value="提交">
    </form>
<%--    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">--%>
<%--        <input type="hidden" name="bookID" value="${uBook.bookID}"/>--%>
<%--        书籍名称:<input type="text" name="bookName" value="${uBook.bookName}"/>--%>
<%--        书籍数量:<input type="text" name="bookCounts" value="${uBook.bookCounts}"/>--%>
<%--        书籍详情:<input type="text" name="detail" value="${uBook.detail}"/>--%>
<%--        <input type="submit" value="提交"/>--%>
<%--    </form>--%>

</div
</body>
</html>

登录界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>新增书籍</title>
  <style type="text/css">
    a {
      text-decoration: none;
      color: black;
      font-size: 18px;
    }
    h3 {
      width: 180px;
      height: 38px;
      margin: 100px auto;
      text-align: center;
      line-height: 38px;
      background: deepskyblue;
      border-radius: 4px;
    }
    form{
      margin: 100px auto;
      text-align: center;
    }

  </style>
</head>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<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/login" method="post">
    用户名:<input type="text" name="username"><br><br><br>&nbsp&nbsp&nbsp&nbsp码:<input type="text" name="password"><br><br><br>
    <input type="submit" value="登录">
  </form>
</div>
</body>
</html>

遇到的问题

  • BookMapper.xml中的id要与映射类的方法名相同。
  • 不能直接使用注解将mapper层的接口直接注入到IOC容器中,应该用MapperScannerConfigurer类动态的将接口注入到容器中,同时生成接口的动态代理对象。
  • 使用junit测试时,不能直接调用业务层类测试,需要使用ClassPathXmlApplicationContext类。

总结

这是一个小图书管理的小demo,实现了登录界面,以及对图书的增删改查操作。

项目截图
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值