@GetMapping("/list/{id}")
public String handleCategoryListRequest(@PathVariable("id") Integer id, Model model, Principal principal) {
Category category = this.categoryService.getList(id);
model.addAttribute("category", category);
// 도서 목록 조회 (예시)
List<Book> books = bookRepository.findAll(); // 또는 다른 방식으로 도서 목록을 조회
model.addAttribute("books", books); // 도서 목록을 모델에 추가
if (principal != null) {
Member member = this.memberService.getList(Integer.valueOf(principal.getName()));
model.addAttribute("member", member);
}
return "book/books";
}```
코드를 입력하세요
@Controller
@RequiredArgsConstructor
public class BookController {
private final BookService bookService;
private final BookRepository bookRepository;
private final CategoryRepository categoryRepository;
private final CategoryService categoryService;
@GetMapping("book/detail/{id}") //책에 대한 상세페이지
public String bookDetail(Model model, @PathVariable("id") Integer id) {
Book book = this.bookService.getList(id);
model.addAttribute("book", book);
return "book/book_detail";
}
@GetMapping("category/list/{id}/create")
public String bookCreate(Model model) {
model.addAttribute("bookForm", new BookForm());
List<Category> categories = categoryService.getAllCategories(); // 카테고리 목록 가져오기
model.addAttribute("categories", categories); // 카테고리 목록 전달
return "book/book_create_form";
}
@PostMapping("category/list/{id}/create")
public String bookCreate(@PathVariable("id") Integer id,@Valid BookForm bookForm, BindingResult bindingResult,
@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return "/book_create_form";
}
// 이미지 업로드 로직 추가
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
String category = String.valueOf(bookForm.getCategory()); // 폼에서 선택된 카테고리 정보 가져오기
Book book = bookService.createWithImage(bookForm.getSubject(), bookForm.getContent(),
bookForm.getBookIntroduce(),
bookForm.getAuthor(),
bookForm.getCategory(),
bookForm.getPrice(),
bookForm.getDiscount(),
bookForm.getPublisher(),file);
redirectAttributes.addFlashAttribute("success", "도서가 성공적으로 등록되었습니다.");
// 카테고리 페이지로 리다이렉트
return String.format("redirect:/category/list/%s", id);
} catch (IOException e) {
redirectAttributes.addFlashAttribute("error", "도서 등록에 실패하였습니다.");
}
return String.format("redirect:/category/list/%s", id);
}