turns-00056.parquet:41763
6914cde085c57e5d76e8d3df
turn 2/4gpt-4o-mini-2024-07-18EnglishFrance2021 words
degenerate_repetitionAbsentFinal dense release
USER
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户页面</title>
<link href="./css/user.css" rel="stylesheet" type="text/css">
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(to right, #e2e3e5, #ffffff);
margin: 0;
color: #333;
}
.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>
</head>
<body>
<div class="topbar">
<div>用户:<span id="username-display">未登录</span></div>
<button onclick="logout()">退出</button>
</div>
<div class="sidebar">
<h1>用户菜单</h1>
<button onclick="showSection('search')">搜索书籍</button>
<button onclick="showSection('history')">借阅历史</button>
<button onclick="showSection('favorites')">我的收藏</button>
</div>
<div class="main-content">
<div class="section" id="searchSection">
<div class="form-container">
<h1>搜索书籍</h1>
<input type="text" id="searchInput" placeholder="搜索书名或作者">
<button class="query-button" onclick="searchBooks()">查询</button>
</div>
<div id="searchResults" class="search-results-container"></div>
</div>
<div class="section" id="historySection" style="display:none;">
<h1>借阅历史</h1>
<ul class="book-list" id="borrowHistory"></ul>
</div>
<div class="section" id="favoritesSection" style="display:none;">
<h1>我的收藏</h1>
<ul class="book-list" id="favoritesList"></ul>
</div>
</div>
<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' // 声明使用 JSON 格式
},
body: JSON.stringify({ keyword }) // 将关键词封装成 JSON 发送到后端
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json(); // 解析 JSON 数据
})
.then(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.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;
}
function checkBorrowHistory(userId) {
return fetch(`http://localhost:8080/api/borrow-records/user/borrow-history/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('未找到借阅记录');
}
return response.json();
})
.catch(error => {
console.error('Error fetching borrow history:', error);
alert('获取借阅历史时发生了错误, 请稍后再试');
return []; // 返回空数组以避免未定义错误
});
}
// 借阅书籍
function borrowBook(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 检查借阅历史
checkBorrowHistory(userId)
.then(borrowRecords => {
if (borrowRecords.length > 0) {
alert('您有借阅记录,无法借阅新的书籍!');
return;
}
// 如果没有借阅记录,继续执行借阅操作
return fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId })
});
})
.then(response => {
if (!response) {
throw new Error('借阅请求未发送');
}
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
alert('您已成功借阅');
loadBorrowHistory();
})
.catch(error => {
console.error('Error:', error);
alert('借阅书籍时发生错误,请稍后再试');
});
}
// 加载借阅历史
function loadBorrowHistory() {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 更新 API 路径
fetch(`http://localhost:8080/api/borrow-records/user/borrow-history/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('未找到借阅记录');
}
return response.json();
})
.then(data => {
displayBorrowHistory(data);
})
.catch(error => {
console.error('Error:', error);
alert('加载借阅历史时发生错误,请稍后再试');
});
}
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 || Date.now()); // 若 borrow_date 为 null, 使用当前时间
const formattedDate = borrowDate.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
listItem.textContent = `书名: ${record.title || '未知'} - 作者: ${record.author || '未知'} - 借阅日期: ${formattedDate} - 状态: ${record.is_returned ? '已还书' : '未还书'}`;
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.is_returned) {
returnButton.disabled = true;
returnButton.textContent = '已还书';
}
listItem.appendChild(returnButton);
borrowHistory.appendChild(listItem);
});
}
}
function returnBook(borrowRecordId, returnButton) {
const userId = getUserId();
if (!userId || !borrowRecordId) {
alert('无效的用户 ID 或借阅记录 ID');
return;
}
returnButton.disabled = true;
returnButton.textContent = '处理中...';
fetch(`http://localhost:8080/api/borrow-records/return/${borrowRecordId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.text(); // 使用 .text() 解析文本响应
})
.then(data => {
console.log(data)
alert(data); // data 是字符串格式的消息
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) {
return response.text().then(text => {
throw new Error('添加收藏时发生错误:' + text);
});
}
return response.json();
})
.then(data => {
alert('已成功添加到收藏!');
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('添加收藏时发生错误,请稍后再试');
});
}
// 加载收藏书籍
function loadFavorites() {
const userId = getUserId();
console.log('加载收藏的用户ID:', userId); // 增加调试信息
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch(`http://localhost:8080/api/favorites/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
displayFavorites(data); // 确保数据结构正确
})
.catch(error => {
console.error('Error:', error);
alert('加载收藏时发生错误,请稍后再试');
});
}
// 显示收藏书籍
function displayFavorites(favoriteBooks) {
const favoritesList = document.getElementById('favoritesList');
favoritesList.innerHTML = '';
if (favoriteBooks.length === 0) {
favoritesList.innerHTML = '<p>没有收藏的书籍</p>';
} else {
const userId = getUserId(); // 获取用户 ID
checkBorrowHistory(userId)
.then(borrowRecords => {
const hasBorrowed = borrowRecords.length > 0; // 检查是否有借阅记录
favoriteBooks.forEach(favorite => {
const listItem = document.createElement('li');
listItem.innerHTML = `书名: ${favorite.bookTitle} - 作者: ${favorite.bookAuthor}`;
const borrowButton = document.createElement('button');
borrowButton.textContent = hasBorrowed ? '借阅' : '借阅';
borrowButton.disabled = hasBorrowed; // 如果有借阅记录,禁用借阅按钮
borrowButton.onclick = function () {
borrowFromFavorites(favorite.bookId);
};
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除收藏';
deleteButton.onclick = function () {
removeFromFavorites(favorite.bookId);
};
listItem.appendChild(borrowButton);
listItem.appendChild(deleteButton);
favoritesList.appendChild(listItem);
});
})
.catch(error => {
console.error('Error:', error);
alert('加载收藏时发生错误,请稍后再试');
});
}
}
// 从收藏中借阅书籍
function borrowFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 检查借阅历史
checkBorrowHistory(userId)
.then(borrowRecords => {
if (borrowRecords.length > 0) {
alert('您已借阅记录,无法借阅新的书籍!');
return;
}
return fetch('http://localhost:8080/api/borrow-records/borrow', {
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 => {
alert('借阅成功!');
loadFavorites();
loadBorrowHistory();
})
.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/${userId}/${bookId}`, {
method: 'DELETE', // 使用 DELETE 方法
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error('删除失败:' + text);
});
}
return response.text(); // 获取成功信息
})
.then(data => {
alert(data); // 提示成功
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('删除收藏时发生错误,请稍后再试');
});
}
</script>
</body>
</html> 当借阅书籍有数据时,在点击借阅记录报错 借阅书籍时发生错误,请稍后再试user.html:385
Error: Error: 借阅请求未发送
at user.html:373:23
(匿名) @ user.html:385
Promise.catch
borrowBook @ user.html:384
onclick @ user.html:1package com.example.librarysystem.controller;
//
import com.example.librarysystem.entity.BorrowRecord;
import com.example.librarysystem.mapper.BorrowRecordsMapper;
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.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/borrow-records")
public class BorrowRecordController {
@Autowired
private BorrowRecordService borrowRecordService;
@Autowired
private BorrowRecordsMapper borrowRecordsMapper;
@PostMapping("/borrow")
public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
try {
BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
return new ResponseEntity<>(savedRecord, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/user/borrow-history/{userId}")
public ResponseEntity<List<Map<String, Object>>> getBorrowHistoryByUserId(@PathVariable Long userId) {
List<Map<String, Object>> records = borrowRecordsMapper.findBorrowHistoryByUserId(userId);
return new ResponseEntity<>(records, HttpStatus.OK);
}
@GetMapping()
public ResponseEntity<List<BorrowRecord>> getBorrowRecords() {
List<BorrowRecord> records = borrowRecordService.getBorrowRecords();
return new ResponseEntity<>(records, HttpStatus.OK);
}
@PostMapping("/return/{id}")
public ResponseEntity<String> returnBook(@PathVariable Long id) {
try {
borrowRecordService.returnBook(id);
return new ResponseEntity<>("还书成功", HttpStatus.OK); // 直接返回字符串
} catch (Exception e) {
return new ResponseEntity<>("还书失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@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.service;
//
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.time.LocalDateTime;
import java.util.List;
@Service
public class BorrowRecordService {
@Autowired
private BorrowRecordsMapper borrowRecordMapper;
public BorrowRecord borrowBook(BorrowRecord borrowRecord) {
if (borrowRecord.getBorrowDate() == null) {
borrowRecord.setBorrowDate(LocalDateTime.now()); // 设置当前时间为借阅时间
}
borrowRecordMapper.insert(borrowRecord);
return borrowRecord;
}
public List<BorrowRecord> getBorrowRecordsByUserId(Long userId) {
return borrowRecordMapper.selectList(
Wrappers.<BorrowRecord>lambdaQuery().eq(BorrowRecord::getUserId, userId)
);
}
public void returnBook(Long recordId) {
BorrowRecord record = borrowRecordMapper.selectById(recordId);
if (record == null) {
throw new RuntimeException("未找到借阅记录");
}
record.setIsReturned(true);
record.setReturnDate(LocalDateTime.now().toString()); // 或者可以根据需要设定返回日期格式
borrowRecordMapper.updateById(record);
}
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;
}
}修改代码,让他能够正确实现逻辑ASSISTANT
为了让代码能够正确实现借阅书籍的逻辑,并避免在借阅记录存在时出现错误,我们会修复 JavaScript 和后端的代码,确保相应的请求得到及时和正确的处理。
### 1. JavaScript - 更新借阅逻辑
在你的借阅逻辑中,当用户尝试借阅书籍时,你应该从借阅历史中筛选出记录,以确保用户未借阅任何书籍。反复检查你的逻辑,确保不会因为状态处理不当而出现错误。
以下是对 `borrowBook`, `borrowFromFavorites`, 和 `checkBorrowHistory` 的修改,以更好地处理借阅逻辑。
#### 更新 `borrowBook` 函数
```javascript
function borrowBook(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 查询借阅历史
checkBorrowHistory(userId)
.then(borrowRecords => {
if (borrowRecords.length > 0) {
alert('您已经有借阅记录,无法借阅新的书籍!');
return; // 不再继续借阅
}
return fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: userId,
bookId: bookId,
borrowDate: new Date().toISOString() // 添加借阅日期
})
});
})
.then(response => {
if (!response.ok) {
// 捕抓并处理响应中的错误
throw new Error('借阅请求未发送');
}
return response.json();
})
.then(data => {
alert('您已成功借阅');
loadBorrowHistory(); // 更新借阅历史显示
})
.catch(error => {
console.error('Error:', error);
alert('借阅书籍时发生错误,请稍后再试');
});
}
```
#### 更新 `checkBorrowHistory` 函数
确保你的 `checkBorrowHistory` 会正确处理可能的错误并返回有效的数据。
```javascript
function checkBorrowHistory(userId) {
return fetch(`http://localhost:8080/api/borrow-records/user/borrow-history/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('未找到借阅记录');
}
return response.json();
})
.catch(error => {
console.error('Error fetching borrow history:', error);
alert('获取借阅历史时发生了错误,请稍后再试');
return []; // 返回空数组,以避免未定义错误
});
}
```
### 2. 后端 - 更新 `borrowBook` 控制器逻辑
在 Java 后端代码中,要确保借阅记录的创建逻辑和检查都是有效的,避免出现未处理的异常。
确保在借阅书籍时,`borrowBook` 方法正确执行并将借阅记录保存下来。
```java
@PostMapping("/borrow")
public ResponseEntity<?> borrowBook(@RequestBody BorrowRecord borrowRecord) {
try {
// 确保借阅记录必须有用户ID和书籍ID
if (borrowRecord.getUserId() == null || borrowRecord.getBookId() == null) {
return new ResponseEntity<>("用户 ID 和 书籍 ID 不能为空", HttpStatus.BAD_REQUEST);
}
// 添加借阅日期,如果没有指定
if (borrowRecord.getBorrowDate() == null) {
borrowRecord.setBorrowDate(LocalDateTime.now());
}
// 保存借阅记录
BorrowRecord savedRecord = borrowRecordService.borrowBook(borrowRecord);
return new ResponseEntity<>(savedRecord, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("借阅图书失败:" + e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
```
### 3. 后端 - 确保借阅检查机制
实现一个方法来检查用户是否已经借阅书籍,如果有,返回特定的响应。
```java
@GetMapping("/user/hasBorrowed/{userId}")
public ResponseEntity<Boolean> hasBorrowed(@PathVariable Long userId) {
List<BorrowRecord> records = borrowRecordService.getBorrowRecordsByUserId(userId);
return new ResponseEntity<>(!records.isEmpty(), HttpStatus.OK);
}
```
使用这个 API 在前端检查用户是否已有借阅记录。
### 完整解决方案
上述更改将为你提供更清晰的逻辑流,并避免用户在拥有借阅记录时无法发起借阅的情况。同时在后端修复了借阅记录的处理和检查逻辑,确保请求的有效性。调试并测试这些更改是否解决了你的问题,以达到预期的功能效果。