package com.example.librarysystem.controller; // import…
- User
package 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.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); } @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.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 { // 确保在此处获取有效内容 if (book.getTitle() == null || book.getTitle().isEmpty()) { return new ResponseEntity<>("书名不能为空", HttpStatus.BAD_REQUEST); } Books savedBook = bookService.addBook(book); return new ResponseEntity<>(savedBook, HttpStatus.OK); } catch (Exception e) { System.err.println("添加图书时出错: " + e.getMessage()); // 日志错误信息 return new ResponseEntity<>("添加图书失败:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } // 根据书名删除图书的新接口 @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 { if (keyword != null && !keyword.isEmpty()) { booksList = booksMapper.selectList(Wrappers.<Books>lambdaQuery() .like(Books::getTitle, keyword) // 模糊查询书名 .or() .like(Books::getAuthor, keyword)); // 或者根据作者模糊查询 System.out.println("Total books found: " + booksList.size()); // 打印搜索到的书籍数量 } else { System.out.println("关键词为空"); } } catch (Exception e) { booksList = Collections.emptyList(); // 如果出错,返回空列表 System.err.println("Error during search: " + e.getMessage()); } return new ResponseEntity<>(booksList, HttpStatus.OK); } } 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 { @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; - Assistant
要在借阅记录中点击“还书”时,将未还书的状态改成已还书,您需要对后端的服务和前端的逻辑进行适当修改。以下是可能的修改步骤:
后端修改
- 更新还书记录的 API: 确保在后端实现一个还书的方法,这可以在 类中添加方法来更新借阅记录。例如,将 和 更新为正确的值。
- User
- Assistant
您遇到的错误是因为后端 API 返回的响应是一个简单的字符串(
"还书成功"),而前端代码预计返回 JSON 格式的数据,因此在解析 JSON 时导致了SyntaxError: Unexpected token错误。要解决这个问题,您可以选择以下两种方案中的一种:
方案 1: 返回 JSON 格式的响应
修改后端的
returnBook方法,使其返回一个 JSON 格式的响应。方法如下:@PostMapping("/return/{id}") public ResponseEntity<Map<String, String>> returnBook(@PathVariable Long id) { try { borrowRecordService.returnBook(id); Map<String, String> response = new HashMap<>(); response.put("message", "还书成功"); return new ResponseEntity<>(response, HttpStatus.OK); } catch (Exception e) { Map<String, String> response = new HashMap<>(); response.put("message", "还书失败: " + e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } } - User
- Assistant
如果您希望在弹出框中只显示简单的字符串提示(例如“还书成功”),而不是 JSON 格式的响应(如
{"message":"还书成功"}),您可以直接修改后端的响应格式,并在前端相应地处理。以下是修改步骤:
1. 后端修改
在后端的
returnBook方法中,返回一个简单的字符串响应,而不是 JSON 格式:@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); } }2. 前端修改
在前端的
returnBook函数中,您已经在fetch后使用response.text()方法来处理响应,这一部分不需要更改。只是需要确认在弹出框中直接显示返回的数据: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 => { alert(data); // 直接弹出返回的字符串 loadBorrowHistory(); // 重新加载借阅历史 }) .catch(error => { console.error('Error:', error); alert('还书时发生错误,请稍后再试'); returnButton.disabled = false; returnButton.textContent = '还书'; // 恢复按钮状态 }); }