package com.example.librarysystem.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.librarysystem.entity.Books;
import com.example.librarysystem.mapper.BooksMapper;
import com.example.librarysystem.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/books")
public class BookController {
@Autowired
private BookService bookService;
code Copy code
@Autowired
private BooksMapper booksMapper;
// 添加图书的接口
@PostMapping("/add")
public ResponseEntity<?> addBook(@RequestBody Books book) {
try {
Books savedBook = bookService.addBook(book);
return new ResponseEntity<>(savedBook, HttpStatus.OK);
} catch (Exception e) {
throw new RuntimeException("添加图书失败:" + e.getMessage());
}
}
// 根据书名删除图书的新接口
@PostMapping("/deleteByTitle")
public ResponseEntity<?> deleteBookByTitle(@RequestBody Map<String, String> map, @RequestHeader(value = "user-type", required = false) String userType) {
if (!"admin".equals(userType)) {
return new ResponseEntity<>("权限不足,只有管理员可以删除图书", HttpStatus.FORBIDDEN);
}
String title = map.get("title");
try {
bookService.deleteBookByTitle(title);
return new ResponseEntity<>("Book deleted successfully", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("删除图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteBook(@PathVariable Long id, @RequestHeader(value = "user-type", required = false) String userType) {
if (!"admin".equals(userType)) {
return new ResponseEntity<>("权限不足,只有管理员可以删除图书", HttpStatus.FORBIDDEN);
}
try {
bookService.deleteBook(id);
return new ResponseEntity<>("Book deleted successfully", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("删除图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/{id}")
public ResponseEntity<Books> getBookById(@PathVariable Long id) {
Books book = bookService.getBookById(id);
if (book == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(book, HttpStatus.OK);
}
// 新增根据书名修改图书的接口
@PostMapping("/editByTitle")
public ResponseEntity<?> editBookByTitle(@RequestBody Map<String, String> map) {
String oldTitle = map.get("oldTitle");
String newTitle = map.get("newTitle");
String newAuthor = map.get("newAuthor");
String newYearPublishedStr = map.get("newYearPublished");
int newYearPublished = 0;
try {
if (newYearPublishedStr!= null &&!newYearPublishedStr.isEmpty()) {
newYearPublished = Integer.parseInt(newYearPublishedStr);
}
} catch (NumberFormatException e) {
return new ResponseEntity<>("出版年份格式错误", HttpStatus.BAD_REQUEST);
}
Books newBookInfo = new Books();
newBookInfo.setTitle(newTitle);
newBookInfo.setAuthor(newAuthor);
newBookInfo.setYearPublished(newYearPublished);
try {
bookService.editBookByTitle(oldTitle, newBookInfo);
return new ResponseEntity<>("Book edited successfully", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("修改图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/all")
public ResponseEntity<List<Books>> getBooks() {
List<Books> books = bookService.getBooks();
return new ResponseEntity<>(books, HttpStatus.OK);
}
@PostMapping("/edit")
public ResponseEntity<?> editBook(@RequestBody Books book) {
Books editedBook = bookService.editBook(book);
return new ResponseEntity<>(editedBook, HttpStatus.OK);
}
@PostMapping("/search")
public ResponseEntity<List<Books>> searchBooks(@RequestBody Map<String, String> map) {
String keyword = map.get("keyword"); // 获取搜索关键字
System.out.println("Searching for keyword: " + keyword); // 打印接收的关键词
List<Books> booksList = null;
try {
booksList = booksMapper.selectList(Wrappers.<Books>lambdaQuery()
.like(Books::getTitle, keyword) // 书名模糊查询
.or()
.like(Books::getAuthor, keyword)); // 或者作者模糊查询
System.out.println("Total books found: " + booksList.size()); // 调试数量
} catch (Exception e) {
booksList = Collections.emptyList(); // 如果有异常,返回空列表
System.err.println("Error during search: " + e.getMessage()); // 打印错误信息
}
return new ResponseEntity<>(booksList, HttpStatus.OK);
}
}package com.example.librarysystem.controller;
//
import com.example.librarysystem.entity.BorrowRecord;
import com.example.librarysystem.service.BorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/borrow-records")
public class BorrowRecordController {
@Autowired
private BorrowRecordService borrowRecordService;
code Copy code
@PostMapping("/borrow")
public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
return new ResponseEntity<>(savedRecord, HttpStatus.OK);
}
@GetMapping()
public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
return new ResponseEntity<>(records, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
BorrowRecord record = borrowRecordService.getBorrowRecordById(id);
if (record!= null) {
return new ResponseEntity<>(record, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteBorrowRecord(@PathVariable Long id) {
borrowRecordService.deleteBorrowRecord(id);
return new ResponseEntity<>("Borrow record deleted successfully", HttpStatus.OK);
}
@PostMapping("/edit")
public ResponseEntity<?> editBorrowRecord(@RequestBody BorrowRecord borrowRecord) {
BorrowRecord editedRecord = borrowRecordService.editBorrowRecord(borrowRecord);
return new ResponseEntity<>(editedRecord, HttpStatus.OK);
}
}package com.example.librarysystem.controller;
import com.example.librarysystem.entity.Favorite;
import com.example.librarysystem.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/favorites")
public class FavoriteController {
@Autowired
private FavoriteService favoriteService;
code Copy code
@PostMapping("/add")
public ResponseEntity<?> addFavorite(@RequestBody Favorite favorite) {
Favorite savedFavorite = favoriteService.addFavorite(favorite);
return new ResponseEntity<>(savedFavorite, HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteFavorite(@PathVariable Long id) {
favoriteService.deleteFavorite(id);
return new ResponseEntity<>("Favorite deleted successfully", HttpStatus.OK);
}
@GetMapping("/{userId}")
public ResponseEntity<List<Favorite>> getFavoritesByUserId(@PathVariable Long userId) {
List<Favorite> favorites = favoriteService.getFavoritesByUserId(userId);
return new ResponseEntity<>(favorites, HttpStatus.OK);
}
}package com.example.librarysystem.controller;
import com.example.librarysystem.entity.Users;
import com.example.librarysystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
code Copy code
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody Users user) {
Users foundUser = userService.login(user.getUsername(), user.getPassword());
if (foundUser!= null) {
return new ResponseEntity<>(foundUser, HttpStatus.OK);
} else {
return new ResponseEntity<>("Invalid login", HttpStatus.BAD_REQUEST);
}
}
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody Users user) {
Users savedUser = userService.register(user);
return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
}
@GetMapping("/all")
public ResponseEntity<List<Users>> getUsers() {
List<Users> users = userService.getUsers();
return new ResponseEntity<>(users, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<Users> getUserById(@PathVariable Long id) {
Users user = userService.getUserById(id);
if (user!= null) {
return new ResponseEntity<>(user, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return new ResponseEntity<>("User deleted successfully", HttpStatus.OK);
}
@PostMapping("/edit")
public ResponseEntity<?> editUser(@RequestBody Users user) {
System.out.println("接收到的编辑用户信息: " + user);
Map<String, Object> result = userService.editUser(user);
if (Boolean.TRUE.equals(result.get("success"))) {
return new ResponseEntity<>(user, HttpStatus.OK);
} else {
return new ResponseEntity<>(result.get("message"), HttpStatus.BAD_REQUEST);
}
}
}package com.example.librarysystem.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
/**
@author xxx
@since 2024-12-23
*/
@Getter
@Setter
public class Books implements Serializable {
code Copy code
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String title;
private String author;
@TableField(value = "year_published")
private Integer yearPublished;
public Integer getYear_published(){
return yearPublished;
}
public void setYear_published(Integer yearPublished){
this.yearPublished = yearPublished;
}
}
package com.example.librarysystem.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
/**
@author xxx
@since 2024-12-23
*/
@Getter
@Setter
@TableName("borrow_records")
public class BorrowRecord implements Serializable {
code Copy code
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Integer userId;
private Integer bookId;
private LocalDateTime borrowDate;
private String returnDate;
private Boolean isReturned;
private String status;
}
package com.example.librarysystem.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
/**
@author xxx
@since 2024-12-23
*/
@Getter
@Setter
public class Users implements Serializable {
code Copy code
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String role;
}
package com.example.librarysystem.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.librarysystem.entity.Books;
import com.example.librarysystem.mapper.BooksMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
code Copy code
@Autowired
private BooksMapper bookMapper;
public Books addBook(Books books) {
try {
// 可以添加日志打印出版年份的值,便于排查问题
System.out.println("准备插入图书的出版年份: " + books.getYearPublished());
bookMapper.insert(books);
return books;
} catch (Exception e) {
throw new RuntimeException("图书插入数据库失败", e);
}
}
public void deleteBook(Long id) {
int rowsAffected = bookMapper.deleteById(id);
if (rowsAffected == 0) {
throw new RuntimeException("删除图书失败,可能该图书不存在或删除操作出现问题");
}
}
public void deleteBookByTitle(String title) {
Books book = bookMapper.selectOne(Wrappers.<Books>lambdaQuery().eq(Books::getTitle, title));
if (book == null) {
throw new RuntimeException("要删除的图书不存在");
}
int rowsAffected = bookMapper.deleteById(book.getId());
if (rowsAffected == 0) {
throw new RuntimeException("删除图书失败,可能删除操作出现问题");
}
}
public List<Books> getBooks() {
List<Books> booksList = bookMapper.selectList(null);
for (Books book : booksList) {
// 只在出版年份为 null 时设置默认值为 0,避免覆盖正确的出版年份
if (book.getYearPublished() == null) {
book.setYearPublished(0);
}
}
return booksList;
}
public Books getBookById(Long id) {
return bookMapper.selectById(id);
}
public Books editBook(Books books) {
if (books.getId() == null) {
throw new RuntimeException("要修改的图书 id 不能为空");
}
// 检查图书是否存在
Books existingBook = bookMapper.selectById(books.getId());
if (existingBook == null) {
throw new RuntimeException("要修改的图书不存在");
}
bookMapper.updateById(books);
return books;
}
// 新增根据书名修改图书的方法
public void editBookByTitle(String oldTitle, Books newBookInfo) {
Books existingBook = bookMapper.selectOne(Wrappers.<Books>lambdaQuery().eq(Books::getTitle, oldTitle));
if (existingBook == null) {
throw new RuntimeException("要修改的图书不存在");
}
// 将找到的图书的信息更新为新的信息
existingBook.setTitle(newBookInfo.getTitle());
existingBook.setAuthor(newBookInfo.getAuthor());
existingBook.setYearPublished(newBookInfo.getYearPublished());
bookMapper.updateById(existingBook);
}
}package com.example.librarysystem.service;
//
import com.example.librarysystem.entity.BorrowRecord;
import com.example.librarysystem.mapper.BorrowRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BorrowRecordService {
@Autowired
private BorrowRecordsMapper borrowRecordMapper;
code Copy code
public BorrowRecord borrowBook(BorrowRecord borrowRecord) {
borrowRecordMapper.insert(borrowRecord);
return borrowRecord;
}
public List<BorrowRecord> getBorrowRecords() {
return borrowRecordMapper.selectList(null);
}
public BorrowRecord getBorrowRecordById(Long id) {
return borrowRecordMapper.selectById(id);
}
public void deleteBorrowRecord(Long id) {
borrowRecordMapper.deleteById(id);
}
public BorrowRecord editBorrowRecord(BorrowRecord borrowRecord) {
borrowRecordMapper.updateById(borrowRecord);
return borrowRecord;
}
}package com.example.librarysystem.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
/**
@author xxx
@since 2024-12-23
*/
@Getter
@Setter
public class Favorite implements Serializable {
code Copy code
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Integer userId;
private Integer bookId;
}
package com.example.librarysystem.service;
import com.example.librarysystem.entity.Favorite;
import com.example.librarysystem.mapper.FavoritesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FavoriteService {
@Autowired
private FavoritesMapper favoriteMapper;
code Copy code
public Favorite addFavorite(Favorite favorite) {
favoriteMapper.insert(favorite);
return favorite;
}
public void deleteFavorite(Long id) {
favoriteMapper.deleteById(id);
}
public List<Favorite> getFavoritesByUserId(Long userId) {
return favoriteMapper.selectList(null);
}
}
code Copy code
<script>
document.addEventListener("DOMContentLoaded", function () {
updateUsernameDisplay();
});
function logout() {
alert('已退出登录');
localStorage.removeItem('userInfo');
localStorage.removeItem('username');
updateUsernameDisplay();
window.location.href = 'login.html';
}
function updateUsernameDisplay() {
const username = localStorage.getItem('username');
const usernameDisplay = document.getElementById('username-display');
if (username) {
usernameDisplay.textContent = username;
} else {
usernameDisplay.textContent = '未登录';
console.log('在 localStorage 中未找到用户名');
}
}
function showSection(section) {
const sections = document.querySelectorAll('.section');
sections.forEach(s => s.style.display = 'none');
document.getElementById(section + 'Section').style.display = 'block';
if (section === 'favorites') {
loadFavorites();
} else if (section === 'history') {
loadBorrowHistory();
}
}
function searchBooks() {
const keyword = document.getElementById('searchInput').value.trim();
if (keyword === '') {
alert('请输入搜索关键词');
return;
}
// 移除可能的特殊字符
const sanitizedKeyword = keyword.replace(/[%_]/g, ''); // 取值时只允许正常字符串
fetch('http://localhost:8080/api/books/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: sanitizedKeyword }) // 使用处理后的关键词
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => console.error('Error:', error));
}
function displaySearchResults(books) {
const searchResults = document.getElementById('searchResults');
searchResults.innerHTML = ''; // 清空之前的结果
code Copy code
if (books.length === 0) {
searchResults.innerHTML = '<p>没有找到相关书籍</p>'; // 如果没有匹配结果则消息提示
} else {
books.forEach(book => {
// 在此处您可以添加书籍的展示逻辑
const listItem = document.createElement('div');
listItem.className = 'search-result-item'; // 添加记录项的样式
listItem.innerHTML = `
<div>
<strong>书名:</strong> ${book.title}<br>
<strong>作者:</strong> ${book.author}<br>
<strong>出版年份:</strong> ${book.yearPublished || '未知'}
</div>
<div class="book-actions">
<button onclick="borrowBook(${book.id})">借阅</button>
<button onclick="addToFavorites(${book.id})">添加到收藏</button>
</div>
`;
searchResults.appendChild(listItem); // 将该书籍结果添加到显示
});
}
}
function getUserId() {
const userInfo = JSON.parse(localStorage.getItem('userInfo'));
return userInfo ? userInfo.id : null;
}
code Copy code
// 借阅书籍
function borrowBook(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 检查书籍是否在收藏中
fetch(`http://localhost:8080/api/borrow-records/borrow${userId}`)
.then(response => response.json())
.then(favorites => {
const isFavorited = favorites.some(fav => fav.book_id === bookId);
if (isFavorited) {
alert('您已经将此书收藏,不能重复借阅!');
return; // 不允许再次借阅
}
// 检查书籍是否已经被借出
return fetch(`http://localhost:8080/user/borrow-history/${userId}`);
})
.then(response => response.json())
.then(borrowedRecords => {
const isAlreadyBorrowed = borrowedRecords.some(record => record.book_id === bookId && !record.is_returned);
if (isAlreadyBorrowed) {
alert('您已借阅此书,必须先还书才能借阅!');
return; // 不允许借阅
}
// 如果没有借过,允许借阅
return fetch('http://localhost:8080/user/borrow-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId })
});
})
.then(response => {
if (response && response.ok) {
return response.text();
} else {
throw new Error('网络响应不正常');
}
})
.then(data => {
alert('您已成功借阅');
loadBorrowHistory();
})
.catch(error => console.error('Error:', error));
}
function borrowFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code Copy code
// 检查用户的借阅历史
fetch(`http://localhost:8080/user/borrow-history/${userId}`)
.then(response => response.json())
.then(borrowedRecords => {
// 检查该书籍是否已经被借阅
const isAlreadyBorrowed = borrowedRecords.some(record => record.book_id === bookId && !record.is_returned);
if (isAlreadyBorrowed) {
alert('您已借阅此书,必须先还书才能借阅!');
return; // 不允许借阅
}
// 在借阅前检查用户的收藏
fetch(`http://localhost:8080/user/favorites/${userId}`)
.then(response => response.json())
.then(favorites => {
const isFavorited = favorites.some(fav => fav.book_id === bookId);
if (!isFavorited) {
alert('这本书再您的收藏里了');
return; // 不允许借阅
}
// 如果没有借过,允许借阅
fetch('http://localhost:8080/user/borrow-from-favorite', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId })
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
if (data.error) {
alert(data.error);
} else {
alert(data.message);
loadFavorites();
loadBorrowHistory();
}
})
.catch(error => {
console.error('Error:', error);
alert('借阅书籍时发生错误,请稍后再试');
});
})
.catch(error => {
console.error('Error:', error);
alert('获取收藏记录时发生错误,请稍后再试');
});
})
.catch(error => {
console.error('Error:', error);
alert('获取借阅记录时发生错误,请稍后再试');
});
}
// 从收藏中删除书籍
function removeFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code Copy code
fetch('http://localhost:8080/api/favorites/remove', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId })
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
} else {
alert('您已成功从收藏中删除这本书');
loadFavorites();
}
})
.catch(error => console.error('Error:', error));
}
</script>