JavaEE 图书管理系统

news/2024/10/10 23:17:37/

基于阿里巴巴的fastjson框架搭建的JavaEE版本的图书管理系统,项目架构如下:

fastjson包的阿里云下载镜像如下:

Central Repository: com/alibaba/fastjson2/fastjson2/2.0.8 

运行效果:

Bean

Book.java

package Bean;public class Book {private String title;// 书名private String author;// 作者名private double price;// 价格private String type;// 书籍类型private boolean borrowed;// 借阅状态,默认为falsepublic Book(String title, String author, double price, String type) {this.title = title;this.author = author;this.price = price;this.type = type;this.borrowed = false;// 默认为false}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public String getType() {return type;}public void setType(String type) {this.type = type;}public boolean isBorrowed() {return borrowed;}public void setBorrowed(boolean borrowed) {this.borrowed = borrowed;}@Overridepublic String toString() {return "Book{" + "title='" + title + '\'' + ", author='" + author + '\'' + ", price=" + price + ", type='"+ type + '\'' + ", borrowed=" + borrowed + '}';}
}

 Book.java

package Bean;public class User {private String username;// 用户名private String password;// 密码private String role;// 角色public String getUsername() {return username;}public User(String username, String password, String role) {this.username = username;this.password = password;this.role = role;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getRole() {return role;}public void setRole(String role) {this.role = role;}
}

Dao

BookDao

package Dao;import Bean.Book;
import java.util.List;public interface BookDao {// 读取json文件信息List<Book> getAllBooks();// 保存图书信息void saveBooks(List<Book> books);// 添加图书void addBook(Book book);// 删除图书void removeBook(String title);// 查找图书Book findBook(String title);// 更新图书借阅状态void updateBookStatus(String title, boolean borrowed);// 更新图书信息void updateBookDetails(String newTitle, String newAuthor, double newPrice, String newType);
}

UserDao

package Dao;import Bean.User;
import java.util.List;public interface UserDao {// 读取文件信息List<User> getAllUsers();// 添加用户void addUser(User user);// 查找用户User findUser(String username);
}

Dao.Impl 

BookDaoImpl.java 

package Dao.Impl;import Bean.Book;
import Dao.BookDao;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;import java.io.*;
import java.util.ArrayList;
import java.util.List;public class BookDaoImpl implements BookDao {private static final String PATH = "books.txt";/*** @author Stringzhua* @exception 将books通过json解析为List集合中的数据*/@Overridepublic List<Book> getAllBooks() {StringBuilder jsonString = new StringBuilder();try (BufferedReader reader = new BufferedReader(new FileReader(PATH))) {String line;while ((line = reader.readLine()) != null) {jsonString.append(line);}} catch (IOException e) {e.printStackTrace();return new ArrayList<>();}// 从一个json数组字符串中解析出多个jsonObjects,并将存储在一个 List<JSONObject> 中List<JSONObject> jsonObjects = JSON.parseArray(jsonString.toString(), JSONObject.class);List<Book> books = new ArrayList<>();// 遍历list集合for (JSONObject jsonObject : jsonObjects) {Book book = new Book(jsonObject.getString("title"), jsonObject.getString("author"),jsonObject.getDoubleValue("price"), jsonObject.getString("type"));book.setBorrowed(jsonObject.getBooleanValue("borrowed"));books.add(book);}return books;}/*** @author Stringzhua* @exception 保存集合中的所有图书信息到json文件中*/@Overridepublic void saveBooks(List<Book> books) {List<JSONObject> jsonObjects = new ArrayList<>();for (Book book : books) {JSONObject jsonObject = new JSONObject();jsonObject.put("title", book.getTitle());jsonObject.put("author", book.getAuthor());jsonObject.put("price", book.getPrice());jsonObject.put("type", book.getType());jsonObject.put("borrowed", book.isBorrowed());jsonObjects.add(jsonObject);}try (Writer writer = new FileWriter(PATH)) {writer.write(JSON.toJSONString(jsonObjects));} catch (IOException e) {e.printStackTrace();}}// 添加图书方法@Overridepublic void addBook(Book book) {List<Book> books = getAllBooks();books.add(book);saveBooks(books);}// 删除图书@Overridepublic void removeBook(String title) {List<Book> books = getAllBooks();books.removeIf(book -> book.getTitle().equals(title));saveBooks(books);}// 查找图书@Overridepublic Book findBook(String title) {for (Book book : getAllBooks()) {if (book.getTitle().equals(title)) {return book;}}return null;
//		return getAllBooks().stream().filter(book -> book.getTitle().equals(title)).findFirst().orElse(null);}// 借书@Overridepublic void updateBookStatus(String title, boolean borrowed) {List<Book> books = getAllBooks();for (Book book : books) {if (book.getTitle().equals(title)) {book.setBorrowed(borrowed);break;}}// 借书后保存信息到json文件中saveBooks(books);}// 更新图书@Overridepublic void updateBookDetails(String title, String newAuthor, double newPrice, String newType) {List<Book> books = getAllBooks();for (Book book : books) {if (book.getTitle().equals(title)) {book.setAuthor(newAuthor);book.setPrice(newPrice);book.setType(newType);break;}}// 更新后保存到json文件中saveBooks(books);}
}

UserDaoImpl.java 

package Dao.Impl;import Bean.User;
import Dao.UserDao;import java.io.*;
import java.util.ArrayList;
import java.util.List;public class UserDaoImpl implements UserDao {private static final String PATH = "users.txt";/*** @author Stringzhua* @exception 将txt文件中的数据添加到users集合中*/@Overridepublic List<User> getAllUsers() {List<User> users = new ArrayList<>();try (BufferedReader reader = new BufferedReader(new FileReader(PATH))) {String line;while ((line = reader.readLine()) != null) {String[] userInfo = line.split(",");if (userInfo.length == 3) {users.add(new User(userInfo[0], userInfo[1], userInfo[2]));}}} catch (IOException e) {e.printStackTrace();}return users;}/*** @author Stringzhua* @exception 将新注册的用户信息写入到books.txt文件中*/@Overridepublic void addUser(User user) {try (BufferedWriter writer = new BufferedWriter(new FileWriter(PATH, true))) {writer.write(user.getUsername() + "," + user.getPassword() + "," + user.getRole());writer.newLine();} catch (IOException e) {e.printStackTrace();}}/*** @author Stringzhua* @exception 根据username去遍历集合中符合条件的user对象,返回该对象*/@Overridepublic User findUser(String username) {for (User user : getAllUsers()) {if (user.getUsername().equals(username)) {return user;}}// 没有找到return null;
//		return getAllUsers().stream().filter(user -> user.getUsername().equals(username)).findFirst().orElse(null);}
}

Service 

BookService.java

package Service;import Bean.Book;
import java.util.List;//TODO:同名的一本书借书的问题
public interface BookService {// 读取json文件信息List<Book> getAllBooks();// 添加图书void addBook(Book book);// 删除图书void removeBook(String title);// 查找图书Book findBook(String title);// 更新图书借阅状态void updateBookStatus(String title, boolean borrowed);// 更新图书信息void updateBookDetails(String title, String newAuthor, double newPrice, String newType);
}

UserService.java 

package Service;import Bean.User;
import java.util.List;public interface UserService {// 读取文件信息List<User> getAllUsers();// 添加用户void addUser(User user);// 查找用户User findUser(String username);
}

Service.Impl 

BookServiceImpl.java 

package Service.Impl;import Bean.Book;
import Dao.BookDao;
import Service.BookService;
import java.util.List;public class BookServiceImpl implements BookService {private BookDao bookDao;// 有参构造方法public BookServiceImpl(BookDao bookDao) {this.bookDao = bookDao;}// 读取json文件信息@Overridepublic List<Book> getAllBooks() {return bookDao.getAllBooks();}// 添加图书@Overridepublic void addBook(Book book) {bookDao.addBook(book);}// 删除图书@Overridepublic void removeBook(String title) {bookDao.removeBook(title);}// 查找图书@Overridepublic Book findBook(String title) {return bookDao.findBook(title);}// 更新图书借阅状态@Overridepublic void updateBookStatus(String title, boolean borrowed) {bookDao.updateBookStatus(title, borrowed);}// 更新图书信息@Overridepublic void updateBookDetails(String newtitle, String newAuthor, double newPrice, String newType) {bookDao.updateBookDetails(newtitle, newAuthor, newPrice, newType);}
}

 UserServiceImpl.java

package Service.Impl;import Bean.User;
import Dao.UserDao;
import Service.UserService;
import java.util.List;public class UserServiceImpl implements UserService {private UserDao userDao;// 有参构造方法public UserServiceImpl(UserDao userDao) {this.userDao = userDao;}// 读取文件信息@Overridepublic List<User> getAllUsers() {return userDao.getAllUsers();}// 添加用户@Overridepublic void addUser(User user) {userDao.addUser(user);}// 查找用户@Overridepublic User findUser(String username) {return userDao.findUser(username);}
}

Utils 

package Utils;import java.text.SimpleDateFormat;
import java.util.Date;public class Message {// 展示用户名和当前时间public static void WelcomeMessage(String username) {SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String currentTime = formatter.format(new Date());System.out.println("欢迎 " + username + "! 当前时间: " + currentTime);}
}

View 

View.Impl

AdminMenu.java 

package View.Impl;import Bean.Book;
import Service.BookService;import java.util.Scanner;public class AdminMenu {public static void adminMenu(Scanner sc, BookService bookService) {while (true) {System.out.println("图书管理员系统菜单");System.out.println("1. 添加图书");System.out.println("2. 删除图书");System.out.println("3. 编辑图书");System.out.println("4. 查询图书");System.out.println("5. 退出图书管理员系统");System.out.print("请输入选择: ");int choice = sc.nextInt();sc.nextLine(); // 换行switch (choice) {case 1:addBook(sc, bookService);break;case 2:removeBook(sc, bookService);break;case 3:editBook(sc, bookService);break;case 4:searchBook(sc, bookService);break;case 5:return;default:System.out.println("无效的选择,请重新选择!");}}}private static void addBook(Scanner sc, BookService bookService) {System.out.println("============添加书籍============");System.out.print("请输入书名: ");String title = sc.nextLine();System.out.print("请输入作者: ");String author = sc.nextLine();System.out.print("请输入价格: ");double price = sc.nextDouble();sc.nextLine(); // 换行System.out.print("请输入类型: ");String type = sc.nextLine();Book book = new Book(title, author, price, type);bookService.addBook(book);System.out.println(book.getTitle() + "图书添加成功!");}private static void removeBook(Scanner sc, BookService bookService) {System.out.println("============删除书籍============");System.out.print("请输入要删除的书名: ");String title = sc.nextLine();bookService.removeBook(title);System.out.println("图书删除成功!");}private static void editBook(Scanner sc, BookService bookService) {System.out.println("============修改书籍============");System.out.print("请输入要编辑的书名: ");String title = sc.nextLine();Book book = bookService.findBook(title);if (book != null) {System.out.print("请输入新的作者:( 原书作者" + book.getAuthor() + ")");String newAuthor = sc.nextLine();System.out.print("请输入新的价格: (原书价格" + book.getPrice() + ")");double newPrice = sc.nextDouble();sc.nextLine(); // 换行System.out.print("请输入新的类型:(原书类型" + book.getType() + ")");String newType = sc.nextLine();bookService.updateBookDetails(title, newAuthor, newPrice, newType);System.out.println(title + "图书信息更新成功!");} else {System.out.println("书库中未找到这本《" + title + "》,请确认书名是否正确!");}}static void searchBook(Scanner sc, BookService bookService) {System.out.println("查询图书菜单");System.out.println("1. 查询全部图书");System.out.println("2. 按书名查询");System.out.println("3. 按作者查询");System.out.println("4. 按类型查询");System.out.print("请输入选择: ");int choice = sc.nextInt();sc.nextLine(); // 换行switch (choice) {case 1:System.out.println("===========查找所有书籍=============");for (Book book : bookService.getAllBooks()) {System.out.println(book);}break;case 2:System.out.println("===========根据书名查找书籍=============");System.out.print("请输入书名: ");String title = sc.nextLine();for (Book book : bookService.getAllBooks()) {//根据书名查找集合中的book对象if (book.getTitle().contains(title)) {System.out.println(book);}}break;case 3:System.out.println("===========根据作者名查找书籍=============");System.out.print("请输入作者: ");String author = sc.nextLine();for (Book book : bookService.getAllBooks()) {if (book.getAuthor().contains(author)) {//根据作者查找集合中的book对象System.out.println(book);}}break;case 4:System.out.println("===========根据书籍类型名查找书籍=============");System.out.print("请输入类型: ");String type = sc.nextLine();for (Book book : bookService.getAllBooks()) {if (book.getType().contains(type)) {//根据书籍类型查找集合中的book对象System.out.println(book);}}break;default:System.out.println("无效的选择,请重新选择!");}}
}

 BorrowMenu.java

package View.Impl;import Bean.Book;
import Service.BookService;import java.util.Scanner;public class BorrowMenu {public static void userMenu(Scanner sc, BookService bookService) {while (true) {System.out.println("图书借阅系统菜单");System.out.println("1. 借阅图书");System.out.println("2. 归还图书");System.out.println("3. 查询图书");System.out.println("4. 退出图书借阅系统");System.out.print("请输入选择: ");int choice = sc.nextInt();sc.nextLine(); // 换行switch (choice) {case 1:borrowBook(sc, bookService);break;case 2:returnBook(sc, bookService);break;case 3:AdminMenu.searchBook(sc, bookService);break;case 4:return;default:System.out.println("无效的选择,请重新选择!");}}}private static void borrowBook(Scanner sc, BookService bookService) {System.out.println("============借阅书籍============");System.out.print("请输入要借阅的书名: ");String title = sc.nextLine();Book book = bookService.findBook(title);if (book != null && !book.isBorrowed()) {bookService.updateBookStatus(title, true);System.out.println(title + "图书借阅成功!");} else if (book != null && book.isBorrowed()) {System.out.println(title + "该图书已被借阅!");} else {System.out.println("书库中未找到这本《" + title + "》,请确认书名是否正确!");}}private static void returnBook(Scanner sc, BookService bookService) {System.out.println("============归还书籍============");System.out.print("请输入要归还的书名: ");String title = sc.nextLine();Book book = bookService.findBook(title);if (book != null && book.isBorrowed()) {bookService.updateBookStatus(title, false);System.out.println(title + "图书归还成功!");} else if (book != null && !book.isBorrowed()) {System.out.println(title + "该图书未被借阅!");} else {System.out.println("书库中未找到这本《" + title + "》,请确认书名是否正确!");}}
}

MainMenu.java 

package View.Impl;public class MainMenu {public static void MainMenu() {System.out.println("欢迎使用图书管理系统!");System.out.println("1. 登录");System.out.println("2. 注册");System.out.println("3. 退出");System.out.print("请输入选择: ");}
}

 启动类:Application.java

package View;import java.util.Scanner;import Bean.User;
import Dao.Impl.BookDaoImpl;
import Dao.Impl.UserDaoImpl;
import Service.BookService;
import Service.UserService;
import Service.Impl.BookServiceImpl;
import Service.Impl.UserServiceImpl;
import Utils.Message;
import View.Impl.AdminMenu;
import View.Impl.BorrowMenu;
import View.Impl.MainMenu;public class Application {private static BookService bookService = new BookServiceImpl(new BookDaoImpl());private static UserService userService = new UserServiceImpl(new UserDaoImpl());private static User user;public static void main(String[] args) {Scanner sc = new Scanner(System.in);while (true) {MainMenu.MainMenu();int choice = sc.nextInt();sc.nextLine(); // 换行switch (choice) {case 1:login(sc);break;case 2:register(sc);break;case 3:System.out.println("正在退出系统中........");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println();System.out.println("已退出系统,感谢您的使用!再见!");return;default:System.out.println("无效的选择,请重新选择!");}}}private static void login(Scanner sc) {System.out.println("============登录============");System.out.println("管理员用户请使用管理员账户登录");System.out.println("普通用户请使用个人账户登录");System.out.println("==========================");System.out.print("请输入用户名: ");String username = sc.nextLine();System.out.print("请输入密码: ");String password = sc.nextLine();User user = userService.findUser(username);if (user != null && user.getPassword().equals(password)) {user = user;Message.WelcomeMessage(username);// 判断是管理员还是普通用户if ("admin".equals(user.getRole())) {AdminMenu.adminMenu(sc, bookService);} else if ("user".equals(user.getRole())) {BorrowMenu.userMenu(sc, bookService);}} else {System.out.println("用户名或密码错误,请重试!");}}// 用户注册private static void register(Scanner scanner) {System.out.println("============注册============");System.out.print("请输入用户名: ");String username = scanner.nextLine();System.out.print("请输入密码: ");String password = scanner.nextLine();User user = new User(username, password, "user"); // 默认角色是普通用户userService.addUser(user);System.out.println(username + "注册成功,请登录!");}
}

Books.txt

[{"title":"三国演义","author":"罗贯中","price":89.9,"type":"小说","borrowed":false},{"title":"红楼梦","author":"曹雪芹","price":49.8,"type":"小说","borrowed":false},{"title":"java从入门到放弃","author":"黑马程序员","price":90.6,"type":"科学与技术","borrowed":true},{"title":"测试","author":"我","price":96.8,"type":"测试","borrowed":false},{"title":"4","author":"4","price":4.0,"type":"4","borrowed":false},{"title":"1","author":"1","price":1.0,"type":"1","borrowed":true},{"title":"1","author":"1","price":1.0,"type":"1","borrowed":false}]

Users.txt 

admin,admin,admin
user,user,user
1,1,user
2,2,user
3,3,user
4,4,user
1,1,user

http://www.ppmy.cn/news/1506370.html

相关文章

MLP:全连接神经网络的并行执行

目录 MLP:全连接神经网络的并行执行 假设 代码解释 注意事项 MLP:全连接神经网络的并行执行 为了继续解释这段代码,我们需要做一些假设和补充,因为原始代码片段中DummyModel、Shard和mx.array的具体实现没有给出。不过,基于常见的编程模式和深度学习框架的惯例,我们…

电话营销机器人的优势

在人工智能的新趋势下&#xff0c;企业开始放弃传统外呼系统&#xff0c;转而使用电话销售机器人&#xff0c;那么使用机器人比坐席手动外呼好吗&#xff0c;真的可以代替人工坐席外呼吗&#xff0c;效率真的高吗&#xff1f; 1、 真人式语音 电话销售人员可以将自定义的话术…

React前端面试每日一试 6.什么是React的Context API?如何使用它?

React的Context API是一种用于共享组件树中全局数据的方法&#xff0c;而无需通过props逐层传递。它对于需要在应用中许多不同层次上访问数据的情况非常有用&#xff0c;例如当前的主题、用户信息或首选语言。 Context API的核心概念 1.创建Context&#xff1a;使用React.cre…

oracle创建dblink使得数据库A能够访问数据库B表LMEAS_MFG_FM的数据

1、给数据库A普通用户CMRONLINE相应的权限&#xff0c;在sys用户下执行以下语句 GRANT CREATE DATABASE LINK TO CMRONLINE; GRANT DROP PUBLIC DATABASE LINK TO CMRONLINE; GRANT CREATE PUBLIC DATABASE LINK TO CMRONLINE; 2、在数据库A用户 CMRONLINE下执行创建语句&…

目标跟踪那些事

目标跟踪那些事 跟踪与检测的区别 目标跟踪和目标检测是计算机视觉中的两个重要概念&#xff0c;但它们的目的和方法是不同的。 目标检测(object Detection)&#xff1a;是指在图像或视频帧中识别并定位一个或多个感兴趣的目标对象的过程 。 目标跟踪(object Tracking)&…

常用的图像增强操作

我们将介绍如何用PIL库实现一些简单的图像增强方法。 [!NOTE] 初始化配置 import numpy as np from PIL import Image, ImageOps, ImageEnhance import warningswarnings.filterwarnings(ignore) IMAGE_SIZE 640[!important] 辅助函数 主要用于控制增强幅度 def int_param…

数据库之SQL注入

SQL注入&#xff08;SQL Injection&#xff09;是一种代码注入攻击&#xff0c;攻击者通过将恶意SQL代码插入到应用程序的输入参数中&#xff0c;从而操控数据库执行未经授权的操作。这种攻击通常发生在web应用程序上&#xff0c;特别是当应用程序没有正确过滤用户输入时。 一…

LSPatch制作内置模块应用软件无需root 教你制作内置应用

前言 LSPatch功能非常强大&#xff0c;它是一款基于LSPosed核心的免Root Xposed框架软件。这意味着用户无需进行手机root操作&#xff0c;即可轻松植入内置Xposed模块&#xff0c;享受更多定制化的功能和体验&#xff0c;比如微某内置模块版等&#xff0c;这为那些不想root手机…