JavaEE 图书管理系统

基于阿里巴巴的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;// 借阅状态,默认为false

	public 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;
	}

	@Override
	public 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集合中的数据
	 */
	@Override
	public 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文件中
	 */
	@Override
	public 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();
		}
	}

	// 添加图书方法
	@Override
	public void addBook(Book book) {
		List<Book> books = getAllBooks();
		books.add(book);
		saveBooks(books);
	}

	// 删除图书
	@Override
	public void removeBook(String title) {
		List<Book> books = getAllBooks();
		books.removeIf(book -> book.getTitle().equals(title));
		saveBooks(books);
	}

	// 查找图书
	@Override
	public 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);
	}

	// 借书
	@Override
	public 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);
	}

	// 更新图书
	@Override
	public 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集合中
	 */
	@Override
	public 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文件中
	 */
	@Override
	public 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对象,返回该对象
	 */
	@Override
	public 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文件信息
	@Override
	public List<Book> getAllBooks() {
		return bookDao.getAllBooks();
	}

	// 添加图书
	@Override
	public void addBook(Book book) {
		bookDao.addBook(book);
	}

	// 删除图书
	@Override
	public void removeBook(String title) {
		bookDao.removeBook(title);
	}

	// 查找图书
	@Override
	public Book findBook(String title) {
		return bookDao.findBook(title);
	}

	// 更新图书借阅状态
	@Override
	public void updateBookStatus(String title, boolean borrowed) {
		bookDao.updateBookStatus(title, borrowed);
	}

	// 更新图书信息
	@Override
	public 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;
	}

	// 读取文件信息
	@Override
	public List<User> getAllUsers() {
		return userDao.getAllUsers();
	}

	// 添加用户
	@Override
	public void addUser(User user) {
		userDao.addUser(user);
	}

	// 查找用户
	@Override
	public 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 block
					e.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
  • 12
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值