用户注册,登录
对图书进行增删改查
package com.xwr.controller;
import com.xwr.entity.Book;
import com.xwr.entity.Category;
import com.xwr.service.BookService;
import com.xwr.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
/**
* 图书控制器
*/
@Controller
@RequestMapping("/book")
public class BookController {
private final BookService bookService;
private final CategoryService categoryService;
@Autowired
public BookController(BookService bookService, CategoryService categoryService) {
this.bookService = bookService;
this.categoryService = categoryService;
}
/**
* 显示图书列表页面
*/
@GetMapping("/list")
public String list(
@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "author", required = false) String author,
@RequestParam(value = "categoryId", required = false) Integer categoryId,
Model model,
HttpSession session) {
// 检查用户是否已登录
if (session.getAttribute("loginUser") == null) {
// 未登录,重定向到登录页面
return "redirect:/user/login";
}
// 查询分类列表
List<Category> categories = categoryService.findAll();
model.addAttribute("categories", categories);
// 查询条件不为空时,执行条件查询
if (title != null && !title.isEmpty() || author != null && !author.isEmpty() || categoryId != null) {
List<Book> books = bookService.findByCondition(title, author, categoryId);
model.addAttribute("books", books);
model.addAttribute("title", title);
model.addAttribute("author", author);
model.addAttribute("categoryId", categoryId);
} else {
// 执行分页查询
Map<String, Object> pageInfo = bookService.findByPage(pageNum, pageSize);
model.addAttribute("pageInfo", pageInfo);
}
return "book/list";
}
/**
* 显示图书详情页面
*/
@GetMapping("/detail/{id}")
public String detail(@PathVariable("id") Integer id, Model model) {
Book book = bookService.findById(id);
model.addAttribute("book", book);
return "book/detail";
}
/**
* 显示添加图书页面
*/
@GetMapping("/add")
public String showAddForm(Model model) {
List<Category> categories = categoryService.findAll();
model.addAttribute("categories", categories);
return "book/add";
}
/**
* 显示编辑图书页面
*/
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable("id") Integer id, Model model) {
Book book = bookService.findById(id);
List<Category> categories = categoryService.findAll();
model.addAttribute("book", book);
model.addAttribute("categories", categories);
return "book/edit";
}
/**
* 删除图书
*/
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") Integer id) {
bookService.delete(id);
return "redirect:/book/list";
}
}
package com.xwr.controller;
import com.xwr.entity.Book;
import com.xwr.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 图书REST控制器
* 用于处理AJAX请求和文件上传
*/
@RestController
@RequestMapping("/api/book")
public class BookRestController {
private final BookService bookService;
@Autowired
public BookRestController(BookService bookService) {
this.bookService = bookService;
}
/**
* 注册自定义日期编辑器
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
/**
* 添加图书
*/
@PostMapping("/add")
public Map<String, Object> add(Book book, @RequestParam(value = "coverImage", required = false) MultipartFile coverImage, HttpServletRequest request) {
Map<String, Object> result = new HashMap<>();
try {
// 处理上传图片
if (coverImage != null && !coverImage.isEmpty()) {
String uploadPath = request.getServletContext().getRealPath("/upload/");
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
// 生成唯一文件名
String originalFilename = coverImage.getOriginalFilename();
String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + extension;
// 保存文件
File destFile = new File(uploadPath + fileName);
coverImage.transferTo(destFile);
// 设置图片路径
book.setImageUrl("/upload/" + fileName);
}
// 保存图书信息
boolean success = bookService.add(book);
result.put("success", success);
result.put("message", success ? "添加成功" : "添加失败");
result.put("book", book);
} catch (IOException e) {
result.put("success", false);
result.put("message", "上传图片失败: " + e.getMessage());
} catch (Exception e) {
result.put("success", false);
result.put("message", "添加失败: " + e.getMessage());
}
return result;
}
/**
* 更新图书
*/
@PostMapping("/update")
public Map<String, Object> update(Book book, @RequestParam(value = "coverImage", required = false) MultipartFile coverImage, HttpServletRequest request) {
Map<String, Object> result = new HashMap<>();
try {
// 如果有新上传的图片
if (coverImage != null && !coverImage.isEmpty()) {
String uploadPath = request.getServletContext().getRealPath("/upload/");
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
// 生成唯一文件名
String originalFilename = coverImage.getOriginalFilename();
String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + extension;
// 保存文件
File destFile = new File(uploadPath + fileName);
coverImage.transferTo(destFile);
// 设置新的图片路径
book.setImageUrl("/upload/" + fileName);
}
// 更新图书信息
boolean success = bookService.update(book);
result.put("success", success);
result.put("message", success ? "更新成功" : "更新失败");
} catch (IOException e) {
result.put("success", false);
result.put("message", "上传图片失败: " + e.getMessage());
} catch (Exception e) {
result.put("success", false);
result.put("message", "更新失败: " + e.getMessage());
}
return result;
}
/**
* 删除图书
*/
@PostMapping("/delete/{id}")
public Map<String, Object> delete(@PathVariable("id") Integer id) {
Map<String, Object> result = new HashMap<>();
try {
// 删除图书
boolean success = bookService.delete(id);
result.put("success", success);
result.put("message", success ? "删除成功" : "删除失败");
} catch (Exception e) {
result.put("success", false);
result.put("message", "删除失败: " + e.getMessage());
}
return result;
}
}