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;
@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>> getBook(@RequestBody Map<String, String> map) {
String value = map.get("keyword");
List<Books> booksList = null;
try {
booksList = booksMapper.selectList(Wrappers.<Books>lambdaQuery().eq(Books::getTitle, value));
} catch (Exception e) {
booksList = Collections.emptyList();
}
return new ResponseEntity<>(booksList, HttpStatus.OK);
}
}
.topbar {
background-color: #343a40;
color: white;
padding: 15px 20px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
.topbar button {
background-color: #dc3545;
border: none;
color: white;
padding: 10px 15px;
border-radius: 20px;
cursor: pointer;
transition: background-color 0.3s, transform 0.3s;
font-weight: bold;
}
.topbar button:hover {
background-color: #c82333;
transform: scale(1.05);
}
.sidebar {
width: 240px;
background-color: #343a40;
color: white;
padding: 20px;
position: fixed;
top: 75px;
height: calc(100% - 75px);
overflow-y: auto;
box-shadow: 2px 0 10px rgba(0, 0, 0, 0.2);
}
.sidebar h1 {
text-align: center;
font-size: 24px;
margin-bottom: 20px;
font-weight: bold;
}
.sidebar button {
font-size: 16px;
width: 100%;
padding: 12px;
margin: 8px 0;
border: none;
border-radius: 8px;
background-color: #495057;
color: white;
cursor: pointer;
transition: background-color 0.3s;
}
.sidebar button:hover {
background-color: #5a6268;
}
.main-content {
margin-left: 240px;
padding: 25px;
flex-grow: 1;
background-color: #f8f9fa;
margin-top: 75px;
flex-direction: column;
align-items: center;
}
.section {
width: 100%;
max-width: 800px;
margin-bottom: 30px;
text-align: center;
/* background-color: white; */
border-radius: 10px;
/* 圆角 */
/* box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1); */
padding: 20px;
}
.form-container {
padding: 20px;
margin: 0 auto;
}
.form-container input {
width: calc(100% - 30px);
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
margin: 10px 0;
transition: border-color 0.3s;
}
.form-container input:focus {
border-color: #007bff;
outline: none;
}
.query-button {
padding: 12px 20px;
font-size: 16px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: white;
cursor: pointer;
transition: background-color 0.3s, transform 0.3s;
}
.query-button:hover {
background-color: #0056b3;
transform: scale(1.05);
}
.search-results-container {
padding: 20px;
border-radius: 10px;
width: 100%;
margin-top: 20px;
}
.search-result-item {
background-color: white;
padding: 15px;
margin: 10px 0;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.search-result-item div {
flex: 1;
margin-right: 20px;
}
.book-actions button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.book-actions button:hover {
background-color: #0056b3;
}
.book-list {
list-style-type: none;
padding: 0;
width: 100%;
}
.book-list li {
background-color: white;
padding: 15px;
margin: 10px 0;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.book-list button {
background-color: #007bff;
padding: 8px 12px;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
transition: background-color 0.3s, transform 0.3s;
}
.book-list button:hover {
background-color: #0056b3;
transform: scale(1.05);
}
</style>
<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;
if (keyword.trim() === '') {
alert('请输入搜索关键词');
return;
}
fetch('http://localhost:8080/api/books/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: keyword }) // 确保这一行的格式与后端期望的一致
})
.then(response => response.json())
.then(data => {
console.log(data); // 调试输出
displaySearchResults(data);
})
.catch(error => console.error('Error:', error));
}
function displaySearchResults(books) {
const searchResults = document.getElementById('searchResults');
searchResults.innerHTML = '';
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.year_published}
</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;
}
// 借阅书籍
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 loadBorrowHistory() {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch(`http://localhost:8080/user/borrow-history/${userId}`)
.then(response => response.json())
.then(data => {
displayBorrowHistory(data);
})
.catch(error => console.error('Error:', error));
}
function displayBorrowHistory(borrowRecords) {
const borrowHistory = document.getElementById('borrowHistory');
borrowHistory.innerHTML = '';
if (borrowRecords.length === 0) {
borrowHistory.innerHTML = '<p>没有借阅记录</p>';
} else {
borrowRecords.forEach(record => {
const listItem = document.createElement('li');
const borrowDate = new Date(record.borrow_date);
const formattedDate = borrowDate.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
listItem.textContent = `书名: ${record.title} - 作者: ${record.author} - 借阅日期: ${formattedDate} - 状态: ${record.status}`;
const returnButton = document.createElement('button');
returnButton.textContent = '还书';
returnButton.onclick = function () {
console.log('Attempting to return book with Record ID:', record.id);
returnBook(record.id, returnButton);
};
if (record.status === '已还书') {
returnButton.disabled = true;
returnButton.textContent = '已还书';
}
listItem.appendChild(returnButton);
borrowHistory.appendChild(listItem);
});
}
}
function returnBook(borrowRecordId, returnButton) {
const userId = getUserId();
console.log('User ID:', userId);
console.log('Record ID:', borrowRecordId);
if (!userId || !borrowRecordId) {
alert('无效的用户 ID 或借阅记录 ID');
return;
}
console.log("Returning book with Record ID:", borrowRecordId, "for User ID:", userId);
returnButton.disabled = true;
returnButton.textContent = '处理中...';
fetch('http://localhost:8080/user/return-book', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, recordId: borrowRecordId })
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
alert(data.message);
loadBorrowHistory();
})
.catch(error => {
console.error('Error:', error);
alert('还书时发生错误,请稍后再试');
returnButton.disabled = false;
returnButton.textContent = '还书';
});
}
// 添加到收藏
function addToFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch('http://localhost:8080/api/favorites/add', {
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();
}
})
.catch(error => {
console.error('Error:', error);
alert('添加收藏时发生错误,请稍后再试');
});
}
// 加载收藏书籍
function loadFavorites() {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch(`http://localhost:8080/api/favorites/${userId}`)
.then(response => response.json())
.then(data => {
displayFavorites(data);
})
.catch(error => console.error('Error:', error));
}
// 显示收藏书籍
function displayFavorites(favoriteBooks) {
const favoritesList = document.getElementById('favoritesList');
favoritesList.innerHTML = '';
if (favoriteBooks.length === 0) {
favoritesList.innerHTML = '<p>没有收藏的书籍</p>';
} else {
favoriteBooks.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `书名: ${book.title} - 作者: ${book.author}`;
const borrowButton = document.createElement('button');
borrowButton.textContent = '借阅';
borrowButton.onclick = function () {
borrowFromFavorites(book.id);
};
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除收藏';
deleteButton.onclick = function () {
removeFromFavorites(book.id);
};
listItem.appendChild(borrowButton);
listItem.appendChild(deleteButton);
favoritesList.appendChild(listItem);
});
}
}
// 从收藏中借阅书籍
function borrowFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
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; // 不允许借阅
}
// 在借阅前检查用户的收藏
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;
}
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>
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th,
td {
border: 1px solid #ddd;
padding: 12px;
text-align: center;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}
.book-list-container {
margin-top: 20px;
}
.book-list-container h2 {
margin-bottom: 20px;
}
input[type="checkbox"] {
width: 20px;
height: 20px;
margin-right: 10px;
}
.book-list-header {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.book-list-header input[type="checkbox"] {
margin-right: 10px;
}
.book-list-container ul {
list-style-type: none;
padding: 0;
}
.book-list-container li {
display: flex;
align-items: center;
background-color: #fff;
padding: 10px;
border: 1px solid #ddd;
margin-bottom: 10px;
}
.book-item {
display: flex;
align-items: center;
flex-grow: 1;
}
.book-actions {
display: flex;
align-items: center;
margin-left: 10px;
}
.book-actions button {
margin-left: 18px;
}
.user-list-container ul {
list-style-type: none;
padding: 0;
width: 100%;
}
.user-list-container li {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #fff;
padding: 10px;
margin-bottom: 10px;
}
.search-results-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 20px;
/* 卡片之间的间隔 */
margin-top: 20px;
}
.book-card {
background-color: #fff;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
width: 350px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: transform 0.2s;
}
.book-card:hover {
transform: scale(1.05);
}
.book-card h3 {
margin-top: 0;
}
.book-card p {
margin: 5px 0;
}
</div>
</div>
<script>
function logout() {
alert('已退出登录');
window.location.href = 'login.html';
}
function showForm(type, id = null) {
const formContainer = document.getElementById('formContainer');
const welcomeMessage = document.getElementById('welcomeMessage');
formContainer.innerHTML = '';
formContainer.style.display = 'block';
welcomeMessage.style.display = 'none';
switch (type) {
case 'add':
formContainer.innerHTML = `
<h1 style="text-align: center";>增加图书</h1>
<input type="text" placeholder="书名">
<input type="text" placeholder="作者">
<input type="number" placeholder="出版年份">
<div style="text-align: center;">
<button style="padding: 10px 20px; font-size: 16px;" onclick="addBook()">添加</button>
`;
break;
case 'delete':
formContainer.innerHTML = `
<h1 style="text-align: center";>删除图书</h1>
<input type="text" id="bookTitle" placeholder="输入书名" style="width: 96%;" />
<div style="text-align: center;">
<button style="padding: 10px 20px; font-size: 16px;" onclick="deleteBookByTitle()">删除</button>
`;
break;
case 'borrowRecords':
formContainer.innerHTML = `
<div style="text-align: center;">
<h1 style="text-align: center";>借阅记录</h1>
<div id="borrowRecordsList"></div>`;
loadBorrowRecords();
break;
case 'edit':
formContainer.innerHTML = `
<h1 style="text-align: center";>修改图书</h1>
<input type="text" placeholder="旧书名" id="oldTitle">
<input type="text" placeholder="新书名" id="newTitle">
<input type="text" placeholder="新作者" id="newAuthor">
<input type="number" placeholder="新出版年份" id="newYearPublished">
<div style="text-align: center;">
<button style="padding: 10px 20px; font-size: 16px;" onclick="editBookByTitle()">修改</button>
`;
break;
case 'search':
formContainer.innerHTML = `
<div style="text-align: center;">
<h1 style="text-align: center";>查询图书</h1>
<input type="text" placeholder="搜索关键词" id="searchKeyword">
<button style="padding: 10px 20px; font-size: 16px;" onclick="searchBooks()">查询</button>
`;
break;
case 'userManagement':
loadUsers().then(users => {
const userItems = users.map(user => `
<li style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
<span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
<div class="book-actions">
<button onclick="editUserForm('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>编辑</button>
<button onclick="deleteUser('${user.id}')" ${user.role === 'admin' ? 'disabled' : ''}>删除</button>
</div>
</li>`).join("");
formContainer.innerHTML = `
<h1 style="text-align: center;">用户管理</h1>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
${userItems}
</ul>
</div>
`;
});
break;
case 'dataManagement':
formContainer.innerHTML = `
<h2>数据管理</h2>
<!-- 这里可以添加数据管理的相关表单或内容 -->
`;
loadBooks();
break;
case 'borrowRecords':
formContainer.innerHTML = `
<h2 style="text-align: center";>借阅记录</h2>
<!-- 这里可以添加借阅记录的相关表单或内容 -->
`;
break;
case 'editUser':
fetch(`http://localhost:8080/api/users/edit${id}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
})
.then(user => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<input type="hidden" value="${id}" name="id">
<input type="text" placeholder="用户名" value="${user.username}" name="username">
<input type="password" placeholder="密码" name="password">
<select name="role">
<option value="user" ${user.role === 'user' ? 'selected' : ''}>用户</option>
<option value="admin" ${user.role === 'admin' ? 'selected' : ''}>管理员</option>
</select>
<button onclick="editUser(${id})">保存</button>
`;
})
.catch(error => {
console.error('获取用户数据出错:', error);
alert('获取用户数据失败: ' + error.message);
});
break;
case 'deleteUser':
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
deleteUser(id);
}
break;
default:
formContainer.style.display = 'none';
welcomeMessage.style.display = 'block'; // 默认显示欢迎消息
}
}
function deleteBookByTitle() {
const bookTitle = document.getElementById('bookTitle').value; // 获取书名
if (!bookTitle) {
alert('请输入书名以进行删除');
return;
}
fetch('http://localhost:8080/api/books/deleteByTitle', { // 修改接口路径,对应后端新的删除接口
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title: bookTitle })
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.text();
})
.then(data => {
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
alert('删除图书时出错:' + error.message);
});
}
function addBook() {
const formContainer = document.getElementById('formContainer');
const title = formContainer.querySelector('input[placeholder="书名"]').value;
const author = formContainer.querySelector('input[placeholder="作者"]').value;
const yearPublishedInput = formContainer.querySelector('input[placeholder="出版年份"]');
const year_published_str = yearPublishedInput.value;
let year_published;
// 验证出版年份是否为合法数字
if (year_published_str.trim() === '') {
alert('请输入出版年份');
return;
}
if (!isNaN(Number(year_published_str))) {
year_published = parseInt(year_published_str);
} else {
alert('出版年份输入格式不正确,请输入合法的数字');
return;
}
// 调用后端search接口检查书名是否已存在,假设search接口支持按书名精确查询
return fetch('http://localhost:8080/api/books/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title })
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(books => {
const bookExists = books.length > 0; // 如果查询到有结果,说明书名已存在
if (bookExists) {
alert('书名已经存在,无法添加。');
return;
}
// 发送增加图书的请求,包含正确格式的出版年份数据
return fetch('http://localhost:8080/api/books/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin'
},
body: JSON.stringify({ title, author, year_published })
});
})
.then(response => {
// 前端处理整个响应
if (!response.ok) {
return response.json().then(err => {
alert(err.error || '添加图书时出错'); // 不再抛出异常
});
}
return response.text();
})
.then(data => {
alert('图书添加成功:' + data);
formContainer.innerHTML = '';
formContainer.style.display = 'none';
showForm('dataManagement');
})
.catch(error => {
console.error('Error adding book:', error);
});
}
function searchBooks() {
const searchKeyword = document.getElementById('searchKeyword').value;
fetch('http://localhost:8080/api/books/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ keyword: searchKeyword })
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
displaySearchResults(data);
})
.catch(error => {
console.error('Error searching books:', error);
alert('搜索图书时出错:' + error.message);
});
}
function displaySearchResults(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<div>
<button onclick="showForm('search')">返回继续搜索</button>
</div>
<h2>搜索结果</h2>
<div class="search-results-container">
`;
if (books.length === 0) {
formContainer.innerHTML += '<p>未找到图书。</p>';
} else {
books.forEach(book => {
let yearToShow = book.year_published;
if (typeof book.year_published === "string") {
yearToShow = parseInt(book.year_published);
}
formContainer.innerHTML += `
<div class="book-card">
<h3>${book.title}</h3>
<p><strong>作者:</strong> ${book.author}</p>
<p><strong>出版年份:</strong> ${yearToShow}</p>
</div>
`;
});
}
formContainer.innerHTML += `</div>`; // 闭合容器
}
function loadBooks() {
console.log('Starting to load books...');
return fetch('http://localhost:8080/api/books/all')
.then(response => {
console.log('Received response from get-books:', response);
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(books => {
console.log("获取到的图书列表详细信息:", books);
displayBooks(books);
return Promise.resolve();
})
.catch(error => {
console.error('Error loading books:', error);
alert('加载图书时出错:' + error.message);
return Promise.reject(error);
});
}
function displayBooks(books) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = <h2 style="text-align: center;">图书管理</h2> <div class="book-list-container"> <div class="book-list-header"> <input type="checkbox" id="selectAllBooks"> 全选 <button onclick="deleteSelectedBooks()">删除选中</button> </div> <ul id="bookList"> ;
books.forEach(book => {
let yearToShow = book.year_published;
// 仅在year_published为null或undefined或为负数时设置为'暂无出版年份'
if (yearToShow === null || yearToShow === undefined || yearToShow < 0) {
yearToShow = '暂无出版年份';
}
formContainer.innerHTML += <li style="display: flex; align-items: center;"> <div class="book-item" style="flex-grow: 1; display: flex; align-items: center;"> <input type="checkbox" class="bookCheckbox" value="${book.id}"> <strong>书名:</strong> ${book.title} <strong>作者:</strong> ${book.author} <strong>出版年份:</strong> ${yearToShow} </div> <div class="book-actions"> <button onclick="editBookForm('${book.id}')">编辑</button> <button onclick="deleteBook('${book.id}')">删除</button> <!-- 直接调用删除 --> </div> </li>;
});
formContainer.innerHTML += </ul> </div> ;
const selectAllCheckbox = document.getElementById('selectAllBooks');
selectAllCheckbox.addEventListener('change', function () {
const checkboxes = document.querySelectorAll('.bookCheckbox');
checkboxes.forEach(checkbox => {
checkbox.checked = this.checked;
});
});
const bookCheckboxes = document.querySelectorAll('.bookCheckbox');
bookCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', function () {
const allChecked = Array.from(bookCheckboxes).every(cb => cb.checked);
selectAllCheckbox.checked = allChecked;
});
});
}
function deleteSelectedBooks() {
const checkboxes = document.querySelectorAll('.bookCheckbox:checked');
const bookIds = Array.from(checkboxes).map(checkbox => checkbox.value);
if (bookIds.length === 0) {
alert('没有选中任何书籍。');
return;
}
if (confirm('确定要删除选中的书籍吗?此操作不可撤销!')) {
bookIds.forEach(id => {
deleteBook(id);
});
}
}
function loadUsers() {
return fetch('http://localhost:8080/api/users/all')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常,状态码:' + response.status);
}
return response.json();
})
.then(users => {
displayUsers(users);
return users;
})
.catch(error => {
console.error('Error loading users:', error);
alert('加载用户时出错:' + error.message);
// 可以考虑添加重试逻辑,比如延迟一段时间后重试
setTimeout(() => {
loadUsers();
}, 2000);
return [];
});
}
function displayUsers(users) {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = `
<h2 style="text-align: center;">用户管理</h2>
<div class="user-list-container" style="display: flex; flex-direction: column; align-items: center;">
<ul style="list-style-type: none; padding: 0;">
${users.map(user => `
<li style="margin: 10px 0; display: flex; justify-content: space-between; align-items: center;">
<span style="flex-grow: 1; margin-right: 10px;">${user.username}</span>
<div class="book-actions">
<button onclick="editUserForm('${user.id}')" ${user.role === 'admin'? 'disabled' : ''}>编辑</button>
<button onclick="deleteUser('${user.id}', '${user.username}')" ${user.role === 'admin'? 'disabled' : ''}>删除</button>
</div>
</li>
`).join('')}
</ul>
</div>
`;
}
function loadBorrowRecords() {
fetch('http://localhost:8080/api/borrow-records')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(records => {
displayBorrowRecords(records);
})
.catch(error => {
alert('加载借阅记录时出错:' + error.message);
});
}
function displayBorrowRecords(records) {
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = '';
if (records.length === 0) {
borrowRecordsList.innerHTML = '<p>无借阅记录。</p>';
} else {
const table = document.createElement('table');
table.innerHTML = `
<tr>
<th>用户名</th>
<th>书名</th>
<th>作者</th>
<th>借阅日期</th>
<th>还书日期</th>
<th>状态</th>
<th>操作</th>
</tr>
`;
records.forEach(record => {
const borrowDate = new Date(record.borrow_date);
const returnDate = record.return_date ? new Date(record.return_date) : null;
const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
const formattedBorrowDate = borrowDate.toLocaleDateString('zh-CN', options).replace(/\//g, '-');
const formattedReturnDate = returnDate ? returnDate.toLocaleDateString('zh-CN', options).replace(/\//g, '-') : '未还';
const row = document.createElement('tr');
row.innerHTML = `
<td>${record.username}</td>
<td>${record.title}</td>
<td>${record.author}</td>
<td>${formattedBorrowDate}</td>
<td>${formattedReturnDate}</td>
<td>${record.status}</td>
<td style="text-align: center;">
<button onclick="deleteBorrowRecordConfirm(${record.id})">删除</button>
</td>
`;
table.appendChild(row);
});
borrowRecordsList.appendChild(table);
}
}
function deleteUser(id) {
if (confirm(`确定要删除用户ID为${id}的用户吗?此操作不可撤销!`)) {
fetch(`http://localhost:8080/api/users/${id}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' }
})
.then(response => {
if (response.status === 200) {
return response.text();
} else if (response.status === 404) {
throw new Error('用户不存在,无法删除');
} else {
throw new Error('删除用户时出现未知错误,状态码:' + response.status);
}
})
.then(data => {
alert('用户删除成功');
loadUsers(); // 重新加载用户列表
})
.catch(error => {
console.error('Error deleting user:', error);
alert('删除用户时出现错误:' + error.message);
});
}
}
function editUserForm(id) {
fetch(http://localhost:8080/api/users/${id})
.then(response => {
if (!response.ok) {
throw new Error('获取用户信息失败,状态码:' + response.status);
}
return response.json();
})
.then(user => {
console.log('获取到的用户信息:', user);
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = <form id="editUserForm"> <input type="hidden" value="${id}" name="id"> <input type="text" placeholder="用户名" value="${user.username}" name="username"> <input type="password" placeholder="旧密码" name="oldPassword" required> <input type="password" placeholder="新密码" name="newPassword"> <select name="role"> <option value="user" ${user.role === 'user'? 'selected' : ''}>用户</option> <option value="admin" ${user.role === 'admin'? 'selected' : ''}>管理员</option> </select> <button type="button" onclick="editUser(${id})">保存</button> <button type="button" onclick="cancelEditUser()">取消</button> </form> ;
})
.catch(error => {
console.error('编辑用户信息获取出错:', error);
alert('获取用户信息失败,请稍后重试:' + error.message);
});
}
function editUser(id) {
const form = document.querySelector(#editUserForm);
if (!form ||!(form instanceof HTMLFormElement)) {
return;
}
const formData = new FormData(form);
// 处理可能存在格式问题的数据,比如去除密码字段前后空格
formData.set('username', formData.get('username').trim());
formData.set('oldPassword', formData.get('oldPassword').trim());
formData.set('newPassword', formData.get('newPassword').trim());
const data = Object.fromEntries(formData.entries());
// 发送POST请求到/api/users/edit
fetch('http://localhost:8080/api/users/edit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
// 处理错误响应
return response.json().then(err => {
alert('编辑用户失败,原因:' + (err.message || '未知错误'));
});
}
return response.json(); // 假设成功响应也是JSON格式
})
.then(data => {
// 处理成功响应
alert(data.message || '用户信息更新成功');
loadUsers(); // 重新加载用户列表
})
.catch(error => {
console.error('Error editing user:', error);
alert('编辑用户信息时出错,请稍后重试:' + error.message);
});
}
function editBookForm(bookId) {
fetch(http://localhost:8080/api/books/${bookId})
.then(response => {
if (!response.ok) {
throw new Error('未能获取图书信息');
}
return response.json();
})
.then(book => {
const formContainer = document.getElementById('formContainer');
formContainer.innerHTML = <h2>修改图书</h2> <input type="hidden" value="${book.id}" id="bookId"> <input type="text" placeholder="书名" id="newTitle" value="${book.title}"> <input type="text" placeholder="作者" id="newAuthor" value="${book.author}"> <input type="number" placeholder="出版年份" id="newYearPublished" value="${book.yearPublished}"> <button onclick="editBook()">保存</button> <button onclick="cancelEditBook()">取消</button> ;
})
.catch(error => {
alert('获取图书信息失败,请稍后重试:' + error.message);
});
}
function deleteBook(bookId) {
if (!bookId) {
alert('无效的图书ID');
return;
}
fetch(`http://localhost:8080/api/books/${bookId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 加上相应头,确认请求权限
}
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.text();
})
.then(data => {
alert('图书删除成功');
loadBooks(); // 重新加载图书列表
})
.catch(error => {
alert('删除图书时出错:' + error.message);
});
}
function editBook() {
const bookId = document.getElementById('bookId').value;
let newTitle = document.getElementById('newTitle').value;
let newAuthor = document.getElementById('newAuthor').value;
let newYearPublished = document.getElementById('newYearPublished').value;
if (newTitle === '' || newAuthor === '' || newYearPublished === '') {
alert('请填写完整信息');
return;
}
const book = {
id: parseInt(bookId),
title: newTitle,
author: newAuthor,
year_published: parseInt(newYearPublished) // 确保使用合适的字段名称
};
fetch('http://localhost:8080/api/books/edit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'user-type': 'admin' // 请确保权限设置
},
body: JSON.stringify(book)
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.text();
})
.then(data => {
alert('图书修改成功');
loadBooks(); // 刷新书籍列表
})
.catch(error => {
alert('修改图书时出错:' + error.message);
});
}
function editBookByTitle() {
const oldTitle = document.getElementById('oldTitle').value;
const newTitle = document.getElementById('newTitle').value;
const newAuthor = document.getElementById('newAuthor').value;
const newYearPublished = document.getElementById('newYearPublished').value;
if (!oldTitle || !newTitle || !newAuthor || newYearPublished === '') {
alert('请填写完整信息');
return;
}
fetch('http://localhost:8080/api/books/editByTitle', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
oldTitle: oldTitle,
newTitle: newTitle,
newAuthor: newAuthor,
newYearPublished: newYearPublished
})
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常: ' + response.statusText);
}
return response.text();
})
.then(data => {
console.log('Book edited:', data);
alert('图书修改成功');
showForm('dataManagement');
})
.catch(error => {
alert('修改图书时出错:' + error.message);
});
}
function deleteBorrowRecordConfirm(recordId) {
if (!recordId) {
alert('无效的借阅记录ID');
return;
}
if (confirm(`确定要删除借阅记录ID为${recordId}的记录吗?此操作不可撤销!`)) {
deleteBorrowRecord(recordId);
}
}
function deleteBorrowRecord(recordId) {
fetch('http://localhost:8080/api/borrow-records/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: recordId })
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.text();
})
.then(data => {
alert('借阅记录删除成功');
loadBorrowRecords();
})
.catch(error => {
console.error('Error deleting borrow record:', error);
alert('删除借阅记录时出错:' + error.message);
});
}
document.addEventListener('DOMContentLoaded', () => {
fetchCurrentAdmin();
});
// 获取当前管理员信息
function fetchCurrentAdmin() {
fetch('http://localhost:8080/admin/current')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
console.log(data);
document.getElementById('adminName').textContent = `管理员:${data.username}`;
})
.catch(error => {
console.error('获取管理员名错误:', error);
document.getElementById('adminName').textContent = '管理员:未知'; // 出错时处理
});
}
</script>
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 {
@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);
}
} 帮我完成用户的搜索书籍功能