LibrarySystem图书管理系统(九)

完善部分功能

  1. 添加借阅功能
  2. 添加还书功能

第一步:修改mybook.html

<!doctype html>
<html lang="zh">
<script src="js/userJS.js"></script>
<script src="js/searchJS.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<link rel="stylesheet" href="css/bootstrap-3.3.7.min.css">
<script src="js/bootstrap-3.3.7.min.js"></script>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订阅</title>
    <!--<link rel="stylesheet" type="text/css" href="css/styles.css">-->
</head>
<body>
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">
            <a href="#" class="navbar-brand">图书管理系统</a>
        </div>
        <div class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li><a href="indexpage.html">返回首页</a></li>
                <li class="dropdown">
                    <a href="#" id="username" class="dropdown-toggle" data-toggle="dropdown">
                        <script type="text/javascript">
                            online();
                        </script>
                    </a>
                    <ul class="dropdown-menu">
                        <li><a href="updatePwd.html">修改密码</a></li>
                        <li><a href="mybook.html">借阅记录</a></li>
                        <li><a href="login.html" onclick="logout()">退出登录</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div class="panel panel-default">
    <div class="panel-heading">

    </div>
    <table class="table" id="borrowPanel">
        <tr style="font-weight: bold"><td>书名</td><td>作者</td><td>出版社</td><td>借阅状态</td></tr>
        <script type="text/javascript">
            showBorrowBook();
        </script>
    </table>
</div>
</body>
</html>


第二步:修改searchJS.js

function search() {
    var bookName = document.getElementById("searchTxt");

    var data = {};
    data["bookName"] = bookName.value;

    $.ajax({
        url:"search",
        type:"POST",
        data:data,
        dataType:"JSON",
        success:function (result) {
            console.log(result);
            $("#postTable").html("<tr style=\"font-weight:bold\"><td>书名</td><td>作者</td><td>出版社</td><td>借阅状态</td><td>一键借阅</td></tr>");
            $.each(result, function (i, item) {
                var isrent;
                if(item.isrent == 0){
                    isrent = "在架上";
                    $("#postTable").append(
                        '<tr><td>'+item.bookName+'</td><td>'+item.bookWriter+'</td><td>'+item.Publisher+'</td><td>'+isrent+'</td><td><a class="btn btn-primary btn-xs" href="#" role="button" id="'+item.bookId+'" onclick="borrowBook(this)">借阅</a></td></tr>'
                    );
                }else{
                    isrent = "已借出";
                    $("#postTable").append(
                        '<tr><td>'+item.bookName+'</td><td>'+item.bookWriter+'</td><td>'+item.Publisher+'</td><td>'+isrent + '</td><td><a class="btn btn-primary btn-xs" href="#" disabled="true" role="button" id="'+item.bookId+'">借阅</a></td></tr>'
                    );
                }
            })
        },
        error:function () {
            alert("请求出错!")
        }
    });
}

function borrowBook(obj) {
    var data = {};
    data["id"] = obj.id.toString();
    if(confirm("请确定是否借阅这本书?")){
        $.ajax({
            url:"borrowBook",
            type:"POST",
            data:data,
            datType:"JSON",
            success:function (result) {
                if(result == true){
                    alert("成功借阅!");
                    setTimeout('window.location.href="mybook.html"');
                }
            },
            error:function () {
                alert("请求错误!");
            }
        });
    }
}

function showBorrowBook(){
    $.ajax({
        url: "showBorrow",
        type: "GET",
        success: function(response) {
            $.each(response, function(i, item) {
                $("#borrowPanel").append(
                    '<tr><td>'+item.bookName+'</td><td>'+item.bookWriter+'</td><td>'+item.Publisher+'</td><td><a class="btn btn-primary btn-xs" href="#"  role="button" id="'+item.bookId+'" onclick="returnBook(this)" >归还</a></td></tr>');
            });
        },
        error: function(xhr, msg, e) {
            alert("请求失败!");
        }
    });
}

function returnBook(obj) {
    var data={};
    data["id"]=obj.id.toString();
    if(confirm("请确定是否归还这本书?")){
        $.ajax({
            url:"returnBook",
            type:"POST",
            data:data,
            dataType:"JSON",
            success:function (response) {
                if(response == true){
                    setTimeout('window.location.href="mybook.html"');
                }
            },
            error:function (xhr, msg, e) {
                console.log(e);
            }
        });
    }
}


第三步:修改BookMapper

package com.ray.dao;

import com.ray.entity.Book;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Book record);

    int insertSelective(Book record);

    Book selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Book record);

    int updateByPrimaryKey(Book record);

    /**
     * 按书名查询
     */
    List<Book> selectBookByName(@Param("bookName") String bookName);

    /**
     * 借书
     */
    void borrow(@Param("id") Long id, @Param("borrow_person") String userName);

    /**
     * 按借书人查询
     */
    List<Book> selectBookByBorrowPerson(@Param("borrow_person") String PersonName);

    /**
     * 还书 
     */
    void returnBook(@Param("id") Long id);
}


第四步:修改BookMapper.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.ray.dao.BookMapper">
  <resultMap id="BaseResultMap" type="com.ray.entity.Book">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="book_name" jdbcType="VARCHAR" property="bookName" />
    <result column="book_writer" jdbcType="VARCHAR" property="bookWriter" />
    <result column="book_publisher" jdbcType="VARCHAR" property="bookPublisher" />
    <result column="book_isrent" jdbcType="BIGINT" property="bookIsrent" />
    <result column="book_person" jdbcType="VARCHAR" property="bookPerson" />
  </resultMap>
  <sql id="Base_Column_List">
    id, book_name, book_writer, book_publisher, book_isrent, book_person
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from book
    where id = #{id,jdbcType=BIGINT}
  </select>
  <!-- 模糊查询 -->
  <select id="selectBookByName" parameterType="com.ray.entity.Book" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from book
    where book_name like concat('%',#{bookName},'%')
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from book
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.ray.entity.Book">
    insert into book (id, book_name, book_writer, 
      book_publisher, book_isrent, book_person
      )
    values (#{id,jdbcType=BIGINT}, #{bookName,jdbcType=VARCHAR}, #{bookWriter,jdbcType=VARCHAR}, 
      #{bookPublisher,jdbcType=VARCHAR}, #{bookIsrent,jdbcType=BIGINT}, #{bookPerson,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.ray.entity.Book">
    insert into book
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="bookName != null">
        book_name,
      </if>
      <if test="bookWriter != null">
        book_writer,
      </if>
      <if test="bookPublisher != null">
        book_publisher,
      </if>
      <if test="bookIsrent != null">
        book_isrent,
      </if>
      <if test="bookPerson != null">
        book_person,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="bookName != null">
        #{bookName,jdbcType=VARCHAR},
      </if>
      <if test="bookWriter != null">
        #{bookWriter,jdbcType=VARCHAR},
      </if>
      <if test="bookPublisher != null">
        #{bookPublisher,jdbcType=VARCHAR},
      </if>
      <if test="bookIsrent != null">
        #{bookIsrent,jdbcType=BIGINT},
      </if>
      <if test="bookPerson != null">
        #{bookPerson,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.ray.entity.Book">
    update book
    <set>
      <if test="bookName != null">
        book_name = #{bookName,jdbcType=VARCHAR},
      </if>
      <if test="bookWriter != null">
        book_writer = #{bookWriter,jdbcType=VARCHAR},
      </if>
      <if test="bookPublisher != null">
        book_publisher = #{bookPublisher,jdbcType=VARCHAR},
      </if>
      <if test="bookIsrent != null">
        book_isrent = #{bookIsrent,jdbcType=BIGINT},
      </if>
      <if test="bookPerson != null">
        book_person = #{bookPerson,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.ray.entity.Book">
    update book
    set book_name = #{bookName,jdbcType=VARCHAR},
      book_writer = #{bookWriter,jdbcType=VARCHAR},
      book_publisher = #{bookPublisher,jdbcType=VARCHAR},
      book_isrent = #{bookIsrent,jdbcType=BIGINT},
      book_person = #{bookPerson,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>

  <!-- 借书 -->
  <update id="borrow" parameterType="com.ray.entity.Book">
    update book
    set book_isrent=1,book_person=#{borrow_person}
    where id=#{id}
  </update>
  <!-- 还书 -->
  <update id="returnBook" parameterType="com.ray.entity.Book">
    update book
    set book_isrent=0,book_person=''
    where id=#{id}
  </update>
  <!-- 查看订阅的书 -->
  <select id="selectBookByBorrowPerson" parameterType="com.ray.entity.Book" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List"/>
    from book
    where book_person=#{borrow_person}
  </select>
</mapper>


第五步:修改BookService 和 BookServiceImpl

public interface BookService {

    List<Book> selectByName(String bookName);
    Book selectBookById(Long id);
    List<Book> selectBookByBorrowPerson(String PersonName);
    void save(Book book);
    void borrow(Long id,String username);
    void returnBook(Long id);
}
/**
 * @author Ray
 * @date 2018/5/23 0023
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Override
    public List<Book> selectByName(String bookName) {
        List<Book> books = bookMapper.selectBookByName(bookName);
        return books;
    }

    @Override
    public Book selectBookById(Long id) {
        return null;
    }

    @Override
    public List<Book> selectBookByBorrowPerson(String PersonName) {
        List<Book> books = bookMapper.selectBookByBorrowPerson(PersonName);
        return books;
    }

    @Override
    public void save(Book book) {

    }

    @Override
    public void borrow(Long id, String username) {
        bookMapper.borrow(id, username);
    }

    @Override
    public void returnBook(Long id) {
        bookMapper.returnBook(id);
    }
}


第六步:修改BookController

package com.ray.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ray.entity.Book;
import com.ray.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Ray
 * @date 2018/5/23 0023
 */
@Controller
public class BookController {

    @Resource
    private BookService bookService;

    /**
     *  列出所有图书
     */
    @RequestMapping("search")
    @ResponseBody
    public JSONArray searchBook(HttpServletRequest request, HttpServletResponse response){
        String bookName = request.getParameter("bookName");
        System.out.println("search: " + bookName);

        List<Book> books = bookService.selectByName(bookName);

        //创建JSONArray对象
        JSONArray jsonArray = new JSONArray();

        for (Book book : books){
            //创建JSONObject对象
            JSONObject jsonObject = new JSONObject();
            //添加键值对
            jsonObject.put("bookId",book.getId());
            jsonObject.put("bookName",book.getBookName());
            jsonObject.put("bookWriter",book.getBookWriter());
            jsonObject.put("Publisher",book.getBookPublisher());
            jsonObject.put("isrent",book.getBookIsrent());
            jsonArray.add(jsonObject);
        }
        HttpSession session = request.getSession();
        session.setAttribute("searchResult",jsonArray);
        System.out.println("jsonArray: " + jsonArray.toString());

        return jsonArray;
    }

    /**
     *  借阅图书
     */
    @RequestMapping("borrowBook")
    @ResponseBody
    public boolean borrow(HttpServletRequest request, HttpServletResponse response){
        Long id = new Long(request.getParameter("id"));
        System.out.println("request id: " + id);

        Object user = request.getSession().getAttribute("username");
        bookService.borrow(id, user.toString());
        return true;
    }

    /**
     *  显示借阅的图书
     */
    @RequestMapping("showBorrow")
    @ResponseBody
    public JSONArray showBorrow(HttpServletRequest request, HttpServletResponse response){
        Object user = request.getSession().getAttribute("username");
        List<Book> books = bookService.selectBookByBorrowPerson(user.toString());

        JSONArray jsonArray = new JSONArray();
        for(Book book : books){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("bookId",book.getId());
            jsonObject.put("bookName",book.getBookName());
            jsonObject.put("bookWriter",book.getBookWriter());
            jsonObject.put("Publisher",book.getBookPublisher());
            jsonObject.put("isrent",book.getBookIsrent());
            jsonArray.add(jsonObject);
        }
        System.out.println(jsonArray.toString());
        return jsonArray;
    }

    /**
     *  还书
     */
    @RequestMapping("returnBook")
    @ResponseBody
    public boolean returnBook(HttpServletRequest request, HttpServletResponse response){
        Long id = new Long(request.getParameter("id"));
        bookService.returnBook(id);
        return true;
    }
}

第七步:运行测试





猜你喜欢

转载自blog.csdn.net/q343509740/article/details/80421779