Java基于MongoDB实现的图书管理系统

本文档描述了一个使用Java和MongoDB实现的图书管理系统。项目包括五个主要模块:数据库操作、类模型、服务类、servlet及MongoDB工具类。在部署阶段,通过IDEA和Ant生成war包,并部署到Tomcat服务器。

写在前面:图书管理系统适合的数据库应该是MySQL,但产品需要这个功能,所以使用了MongoDB数据库。项目部署时除了使用IDEA生成war,也使用Ant编译源码生成war,不过Ant工具的确强大。外包依赖库使用了gson、jstl、mongo驱动包。

一、项目开发阶段
1、第一个项目模块是数据库操作模块BookDaoImpl
public class BookDaoImpl {

    MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
    MongoCollection<Document> collection = mongoDatabase.getCollection("books");

    public FindIterable<Document> findAllBooks() {
        FindIterable<Document> findIterable = collection.find();
        return findIterable;
    }

    public void addBook(String name, String price, String pnum, String category) {
        Document document = new Document();
        document.append("name", name);
        document.append("price", price);
        document.append("pnum", pnum);
        document.append("category", category);
        collection.insertOne(document);
    }

    public void deleteBook(String id) {
        ObjectId objectId = new ObjectId(id);
        BasicDBObject query = new BasicDBObject("_id", objectId);
        collection.deleteOne(query);
    }

    public FindIterable<Document> findBookById(String id) {
        ObjectId objectId = new ObjectId(id);
        BasicDBObject query = new BasicDBObject("_id", objectId);
        FindIterable<Document> findIterable = collection.find(query);
        return findIterable;
    }

    public void updateBook(String id, String name, String price, String pnum, String category) {
        ObjectId objectId = new ObjectId(id);
        BasicDBObject query = new BasicDBObject("_id", objectId);
        Document update = new Document();
        update.append("name", name);
        update.append("price", price);
        update.append("pnum", pnum);
        update.append("category", category);
        Document document = new Document("$set", update);
        collection.updateOne(query, document);
    }

    public FindIterable<Document> SearchBooks(String name) {
        Bson filter = Filters.eq("name", name);
        FindIterable<Document> findIterable = collection.find(filter);
        return findIterable;
    }

    public PageResult<Book> findBooksByPage(int page) {
        PageResult<Book> pr = new PageResult<>();
        long totalCount = collection.count();
        System.out.println(totalCount);
        pr.setTotalCount(totalCount);
        int totalPage = (int) (totalCount % pr.getPageCount() == 0 ? totalCount / pr.getPageCount() : totalCount / pr.getPageCount() + 1);
        System.out.println(totalPage);
        pr.setTotalPage(totalPage);
        pr.setCurrentPage(page);
        int start = (page - 1) * pr.getPageCount();
        FindIterable<Document> skipBooks = collection.find().limit(pr.getPageCount()).skip(start);
        MongoCursor<Document> cursor = skipBooks.iterator();
        List<Book> books = new ArrayList<>();
        while (cursor.hasNext()) {
            Document next = cursor.next();
            String s = next.toJson();
            Gson gson = new Gson();
            Book book = gson.fromJson(s, Book.class);
            ObjectId id1 = (ObjectId) next.get("_id");
            book.setId(id1);
            books.add(book);
        }
        pr.setList(books);
        return pr;
    }
}
2、第二个模块类模型Book类和PageResult类
public class Book {
    private ObjectId id;
    private String name;
    private String price;
    private String pnum;
    private String category;

    public ObjectId getId() {
        return id;
    }

    public void setId(ObjectId id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getPnum() {
        return pnum;
    }

    public void setPnum(String pnum) {
        this.pnum = pnum;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price='" + price + '\'' +
                ", pnum='" + pnum + '\'' +
                ", category='" + category + '\'' +
                '}';
    }
}
package com.test.model;

import java.util.List;

public class PageResult<T> {
    private List<T> list;
    private long totalCount;
    private int totalPage;
    private int currentPage;
    private int pageCount = 6;

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        this.totalCount = totalCount;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    @Override
    public String toString() {
        return "PageResult{" +
                "list=" + list +
                ", totalCount=" + totalCount +
                ", totalPage=" + totalPage +
                ", currentPage=" + currentPage +
                ", pageCount=" + pageCount +
                '}';
    }
}
3、第三个模块服务类BookServiceImpl
public class BookServiceImpl {
    BookDaoImpl bookDao = new BookDaoImpl();

    public FindIterable<Document> findAllBooks() {
        return bookDao.findAllBooks();
    }

    public void addBook(String name, String price, String pnum, String category) {
        bookDao.addBook(name, price, pnum, category);
    }

    public void deleteBook(String id) {
        bookDao.deleteBook(id);
    }

    public FindIterable<Document> findBookById(String id) {
        return bookDao.findBookById(id);
    }

    public void updateBook(String id, String name, String price, String pnum, String category) {
        bookDao.updateBook(id, name, price, pnum, category);
    }

    public FindIterable<Document> SearchBooks(String name) {
        return bookDao.SearchBooks(name);
    }

    public PageResult<Book> findBooksByPage(int page) {
        return bookDao.findBooksByPage(page);
    }
}
4、第四个模块servlet
  • AddBookServlet
@WebServlet("/AddBookServlet")
public class AddBookServlet extends HttpServlet {

   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.setCharacterEncoding("utf-8");
       String name = request.getParameter("name");
       String price = request.getParameter("price");
       String pnum = request.getParameter("pnum");
       String category = request.getParameter("category");
       BookServiceImpl bookService = new BookServiceImpl();
       bookService.addBook(name, price, pnum, category);
       String contextPath = request.getContextPath();
       response.sendRedirect(contextPath + "/BookListServlet");
   }
}
  • BookListServlet
@WebServlet("/BookListServlet")
public class BookListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = request.getParameter("page");
        if(page==null||"".equals(page)){
            page="1";
        }
        BookServiceImpl bookService = new BookServiceImpl();
        PageResult<Book> pageResult = bookService.findBooksByPage(Integer.parseInt(page));
        request.setAttribute("pageResult", pageResult);
        request.getRequestDispatcher("list.jsp").forward(request, response);
    }
}
  • DeleteBookServlet
@WebServlet("/DeleteBookServlet")
public class DeleteBookServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        BookServiceImpl bookService = new BookServiceImpl();
        bookService.deleteBook(id);
        String contextPath = request.getContextPath();
        response.sendRedirect(contextPath + "/BookListServlet");
    }
}
  • FindBookByIdServlet
@WebServlet("/FindBookByIdServlet")
public class FindBookByIdServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        BookServiceImpl bookService = new BookServiceImpl();
        FindIterable<Document> findIterable = bookService.findBookById(id);
        MongoCursor<Document> iterator = findIterable.iterator();
        Document next = iterator.next();
        String s = next.toJson();
        Gson gson = new Gson();
        Book book = gson.fromJson(s, Book.class);
        ObjectId objectId = (ObjectId) next.get("_id");
        book.setId(objectId);
        request.setAttribute("book", book);
        request.getRequestDispatcher("edit.jsp").forward(request, response);
    }
}
  • SearchBookServlet
@WebServlet("/SearchBookServlet")
public class SearchBookServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        BookServiceImpl bookService = new BookServiceImpl();
        FindIterable<Document> findIterable = bookService.SearchBooks(name);
        MongoCursor<Document> cursor = findIterable.iterator();
        List<Book> books = new ArrayList<>();
        while (cursor.hasNext()) {
            Document next = cursor.next();
            String s = next.toJson();
            Gson gson = new Gson();
            Book book = gson.fromJson(s, Book.class);
            ObjectId id = (ObjectId) next.get("_id");
            book.setId(id);
            books.add(book);
        }
        PageResult<Book> pageResult = new PageResult<>();
        pageResult.setList(books);
        request.setAttribute("pageResult", pageResult);
        request.getRequestDispatcher("list.jsp").forward(request, response);
    }
}
  • UpdateBookServlet
@WebServlet("/UpdateBookServlet")
public class UpdateBookServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String pnum = request.getParameter("pnum");
        String category = request.getParameter("category");
        BookServiceImpl bookService = new BookServiceImpl();
        bookService.updateBook(id, name, price, pnum, category);
        String contextPath = request.getContextPath();
        response.sendRedirect(contextPath + "/BookListServlet");
    }
}
5、第五个MongoDB工具类
public class MongoDBUtil {

    public static MongoDatabase getConnect() {
        MongoClient mongoclient = new MongoClient("localHost", 27017);
        MongoDatabase mongoDatabase = mongoclient.getDatabase("test");
        return mongoDatabase;
    }

//    public static MongoDatabase getConnect() {
//        List<ServerAddress> adds = new ArrayList<>();
//        ServerAddress serverAddress = new ServerAddress("192.168.0.122", 8635);
//        adds.add(serverAddress);
//        List<MongoCredential> credentials = new ArrayList<>();
//        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("rwuser", "admin", "Huawei@123##".toCharArray());
//        credentials.add(mongoCredential);
//        MongoClient mongoClient=new MongoClient(adds,credentials);
//        MongoDatabase mongoDatabase=mongoClient.getDatabase("test");
//        return mongoDatabase;
//    }
}
二、项目部署阶段
1、第一种使用IED打成war包部署到Tomcat

在这里插入图片描述
在这里插入图片描述在这里插入图片描述

二、使用Ant生成war,自动部署到Tomcat的webapps中,提前安装好Ant
  • 将build.xml文件放到工程根目录,使用ant命令编译,以下是build.xml的内容
<?xml version="1.0" encoding="gbk"?>
<project name="OnlineBookStoreMongoDB" default="build" basedir=".">
    <!-- 工程根目录 -->
    <property name="OnlineBookStoreMongoDB.home" value="."/>
    <!-- 工程根名 -->
    <property name="OnlineBookStoreMongoDB.name" value="OnlineBookStoreMongoDB"/>

    <!-- tomcat路径   -->
    <!--
    <property name="tomcat.home" value="D:\Apache Tomcat 9.0.41"/>
     -->
    <property name="tomcat.home" value="/opt/module/apache-tomcat-9.0.45"/>

    <!-- tomcat部署路径 -->
    <property name="webapps.home" value="${tomcat.home}/webapps"/>

    <!-- JAVA源文件路径 -->
    <property name="src.home" value="${OnlineBookStoreMongoDB.home}/src"/>

    <!-- class文件存放位置 -->
    <property name="classes.home" value="${OnlineBookStoreMongoDB.home}/classes"/>

    <!-- 发布文件夹 -->
    <property name="deploy.home" value="${webapps.home}"/>
    <!--
    <property name="deploy.home" value="${webapps.home}/deploy"/>
     -->

    <!-- webRoot路径 -->
    <property name="web.home" value="${OnlineBookStoreMongoDB.home}/web"/>

    <!-- 创建工程路径 -->
    <property name="build.home" value="${OnlineBookStoreMongoDB.home}/build"/>
    <!-- /WEB-INF/classes -->
    <property name="build.classes" value="${OnlineBookStoreMongoDB.home}/WEB-INF/classes"/>
    <!-- /WEB-INF/lib -->
    <property name="build.lib" value="${OnlineBookStoreMongoDB.home}/WEB-INF/lib"/>
    <!-- 工程引用包 -->
    <property name="lib.home" value="${web.home}/WEB-INF/lib"/>


    <!-- 编译工程所需的JAR包 -->
    <path id="compile.classpath">
        <pathelement location="${classes.home}"/>
        <fileset dir="${lib.home}">
            <include name="*.jar"/>
            <include name="*.zip"/>
        </fileset>
        <fileset dir="${tomcat.home}/lib">
            <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/common/classes"/>
    </path>


    <!-- 测试ANT -->
    <target name="help">
        <echo message="Please specify a target![usage:ant'targetname']"/>
        <echo message="Here is a list of possible targets:"/>
        <echo message="  clean-all....Delete build dir,all .class and war files"/>
        <echo message="  perpare....Creates directories if requied"/>
        <echo message="  compile....Compiles source files"/>
        <echo message="  build......Build war file from.class and other files"/>
        <echo message="  deploy......Copy war file to the webapps directory"/>
    </target>


    <!-- 清除 -->
    <target name="clean-all">
        <delete dir="${build.home}"/>
        <delete dir="${classes.home}"/>
        <delete dir="${deploy.home}"/>
        <delete dir="${webapps.home}/${OnlineBookStoreMongoDB.home}" failonerror="false"/>
        <delete dir="${webapps.home}/work/" />
        <delete dir="${webapps.home}/${OnlineBookStoreMongoDB.name}.war"/>
    </target>


    <!-- 准备工作 -->
    <target name="prepare" depends="clean-all">
        <echo message="Tomcat Home=${tomcat.home}"/>
        <echo message="Webapps Home=${webapps.home}"/>
        <echo message="classes Home=${classes.home}"/>
        <echo message="war Home=${deploy.home}"/>
        <echo message="Java src Home=${src.home}"/>

        <mkdir dir="${classes.home}"/>
        <mkdir dir="${deploy.home}"/>

        <mkdir dir="${build.home}"/>
        <mkdir dir="${build.home}/WEB-INF"/>
        <mkdir dir="${build.home}/WEB-INF/classes"/>
        <mkdir dir="${build.home}/WEB-INF/lib"/>
    </target>


    <!-- 编译 -->
    <target name="compile" depends="prepare">
        <javac srcdir="${src.home}" destdir="${classes.home}"  includeantruntime="on"

debug="true">
            <compilerarg line="-encoding UTF-8"/>
            <classpath refid="compile.classpath"/>
        </javac>
    </target>

    <!-- 构建临时工程 -->
    <target name="build" depends="compile">
        <copy todir="${build.home}">
            <fileset dir="${web.home}"/>
        </copy>
        <copy todir="${build.home}/WEB-INF/classes">
            <fileset dir="${classes.home}"/>
        </copy>

        <copy todir="${build.home}/WEB-INF/classes">
            <fileset dir="${src.home}">
                <include name="**/*.properties"/>
                <include name="**/*.prop"/>
            </fileset>
        </copy>

        <jar jarfile="${deploy.home}/${OnlineBookStoreMongoDB.name}.war" basedir="${build.home}"/>
    </target>
    <!-- 发布 -->
    <target name="deploy" depends="build">
        <copy todir="${webapps.home}" file="${deploy.home}/${OnlineBookStoreMongoDB.name}.war"/>
    </target>

</project>

项目GitHub地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值