@RestController
@RequestMapping("/api/books")
public class BookController {
@Autowired
private BookService bookService;
code
@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<>("图书删除成功", 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<>("删除成功的书", 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<>("图书编辑成功", 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("搜索关键字: " + 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("发现的图书总数: " + booksList.size()); // 打印搜索到的书籍数量
} else {
System.out.println("关键词为空");
}
} catch (Exception e) {
booksList = Collections.emptyList(); // 如果出错,返回空列表
System.err.println("搜索时出错: " + e.getMessage());
}
return new ResponseEntity<>(booksList, HttpStatus.OK);
}
} package com.example.librarysystem.service;
code
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) {
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);
}
}查询书籍报错admin.html:394
Error: TypeError: Cannot set properties of null (setting 'innerHTML')
at displaySearchResults (admin.html:399:37)
at admin.html:392:13
(匿名) @ admin.html:394
The error you're seeing, TypeError: Cannot set properties of null (setting 'innerHTML'), indicates that the JavaScript function displaySearchResults is trying to access an element that doesn't exist in the DOM. Specifically, on line 399 of your admin.html, you're trying to set the innerHTML of searchResults, which appears not to have been defined properly in your HTML.
Here’s how to troubleshoot and resolve this issue:
Check the HTML Structure: Ensure there's an element with the id searchResults within the form container in your HTML. You likely need to add a section for displaying search results.
You can modify the container to include the search results area. For example, right after the search input in the search case of showForm, you can add:
Ensure the Search Function Is Triggered: When calling searchBooks(), ensure that the server API is functioning and returning the expected data.
Update displaySearchResults: The displaySearchResults function should now correctly find the searchResults container and populate it with the search results.
Here is how the updated displaySearchResults function will look:
Verify API Response: Make sure the API endpoint being called by searchBooks() is correctly configured and returns valid JSON data. Otherwise, inspect that and handle the error properly within the promise chain.
By ensuring the HTML structure is correct and updating the necessary JavaScript functions, the error should be resolved, allowing search results to populate correctly without the null reference error.
searchResults
innerHTML
以下是排查和解决此问题的步骤:
检查 HTML 结构:确保在你的 HTML 中有一个 id 为 searchResults 的元素。你可能需要在显示搜索结果的地方添加一个部分。