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 {
// 确保在此处获取有效内容
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.dto;
import lombok.Data;
@Data
public class FavoriteDTO {
private Long id;
private Long userId;
private Long bookId;
private String bookTitle; // 书名
private String bookAuthor; // 作者
}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.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomCorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, *");
response.setHeader("Access-Control-Allow-Credentials", "true");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}package com.example.librarysystem.handler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHeader {
code Copy code
@ExceptionHandler(Exception.class)
public ResponseEntity businessExceptionHeader(Exception e) {
return new ResponseEntity(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
}
}
package com.example.librarysystem.mapper;
import com.example.librarysystem.entity.Books;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
Mapper 接口
@author xxx
@since 2024-12-23
*/
@Mapper
public interface BooksMapper extends BaseMapper {
}
52|bookService.|deleteBookByTitle|(title); 52|bookService.|deleteBookByTitle|(title); 52|bookService.|deleteBookByTitle|(title); 52|bookService.|deleteBookByTitle|(title);
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true #开启字段映射
code Copy code
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;
}
; }); formContainer.innerHTML +=
`;
}
function displayBorrowRecords(records) {
const borrowRecordsList = document.getElementById('borrowRecordsList');
borrowRecordsList.innerHTML = '';
code Copy code
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 => {
let borrowDate = null;
try {
borrowDate = new Date(record.borrow_date);
} catch (e) {
console.error('解析借阅日期出错:', e);
}
let returnDate = record.return_date? new Date(record.return_date) : '未还';
const formattedBorrowDate = borrowDate? borrowDate.toLocaleDateString('zh-CN') : '日期格式错误';
const formattedReturnDate = returnDate instanceof Date? returnDate.toLocaleDateString('zh-CN') : '未还';
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.is_returned? '已还' : '未还'}</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());
code Copy code
// 发送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;