Menu



Manage

Cord > Project_Bookmarket_따라하기 전체 다운로드
파일 목록
Project_Bookmarket_따라하기 > BookMarket/src/main/java/com/springboot/controller/BookController.java Lines 182 | 7.1 KB
다운로드

                        package com.springboot.controller;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.File; // 파일 처리용

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; // RequestMethod 추가
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;

import com.springboot.domain.Book;
import com.springboot.service.BookService;
import com.springboot.validator.UnitsInStockValidator; // validator는 그대로 유지
import com.springboot.exception.CategoryException;

import jakarta.validation.Valid;
import com.springboot.validator.BookValidator;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.springboot.exception.BookIdException;

@Controller
@RequestMapping(value = "/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @Value("${file.uploadDir}")
    String fileDir;

    @Autowired
    private BookValidator bookValidator;

    @GetMapping
    public String requestBookList(Model model) {
        List<Book> list = bookService.getAllBookList();
        model.addAttribute("bookList", list);
        return "books";
    }

    @GetMapping("/all")
    public ModelAndView requestAllBooks() {
        ModelAndView modelAndView = new ModelAndView();
        List<Book> list = bookService.getAllBookList();
        modelAndView.addObject("bookList", list);
        modelAndView.setViewName("books");
        return modelAndView;
    }

    @GetMapping("/book")
    public String requestBookById(@RequestParam("id") String bookId, Model model) {
        Book bookById = bookService.getBookById(bookId);
        model.addAttribute("book", bookById);
        return "book";
    }

    @GetMapping("/{category}")
    public String requestBooksbyCategory (@PathVariable("category") String bookCategory, Model model) {
        List<Book> booksByCategory = bookService.getBookListByCategory(bookCategory);
        if(booksByCategory == null || booksByCategory.isEmpty()) {
            throw new CategoryException();
        }
        model.addAttribute("bookList", booksByCategory);
        return "books";
    }

    @GetMapping("/filter/{bookFilter}")
    public String requestBooksbyFilter (@MatrixVariable(pathVar = "bookFilter") Map<String, List<String>> bookFilter, Model model) {
        Set<Book> booksByFilter = bookService.getBookListByFilter(bookFilter);
        model.addAttribute("bookList", booksByFilter);
        return "books";
    }

    @GetMapping("/add")
    public String requestAddBookForm(Model model) {
        model.addAttribute("book", new Book());
        return "addBook";
    }

    @PostMapping("/add")
    public String submitAddNewBook(@Valid @ModelAttribute Book book, BindingResult bindingResult) {
        if(bindingResult.hasErrors())
            return "addBook";
        MultipartFile bookImageFile = book.getBookImage();
        String finalFileName = null;

        if (bookImageFile != null && !bookImageFile.isEmpty()) {
            String originalFilename = bookImageFile.getOriginalFilename();
            if (originalFilename != null && !originalFilename.trim().isEmpty()) {
                finalFileName = new File(originalFilename).getName(); // <--- 순수 파일명 추출!
                File saveFile = new File(fileDir, finalFileName);
                try {
                    bookImageFile.transferTo(saveFile);
                } catch (Exception e) {
                    throw new RuntimeException("도서 이미지 업로드가 실패하였습니다: " + e.getMessage(), e);
                }
            }
        }
        book.setFileName(finalFileName);
        bookService.setNewBook(book);
        return "redirect:/books";
    }

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("addTtitle", "신규 도서 등록");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(bookValidator);
        binder.setAllowedFields("bookId", "name", "unitPrice", "author", "description", "publisher", "category", "unitsInStock", "releaseDate", "condition", "bookImage");
    }

    @ExceptionHandler(value={BookIdException.class})
    public ModelAndView handleError(HttpServletRequest req, BookIdException exception) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("invalidBookId", exception.getBookId());
        mav.addObject("exception", exception);
        mav.addObject("url", req.getRequestURL()+"?"+req.getQueryString());
        mav.setViewName("errorBook");
        return mav;
    }

    // 도서 수정 페이지 출력
    @GetMapping("/update")
    public String getUpdateBookForm(@ModelAttribute("updateBook") Book book, @RequestParam("id") String bookId, Model model) {
        Book bookById = bookService.getBookById(bookId);
        model.addAttribute("book", bookById);
        return "updateForm";
    }

    // 도서 수정 처리
    @PostMapping("/update")
    public String processUpdatewBookForm(@ModelAttribute("updateBook") Book book) {
        MultipartFile bookImage = book.getBookImage();

        if (bookImage!= null && !bookImage.isEmpty()) {
            try {
                String fname = bookImage.getOriginalFilename();
                File saveFile = new File(fileDir, fname);
                bookImage.transferTo(saveFile);
                book.setFileName(fname);
            } catch (Exception e) {
                throw new RuntimeException("Book Image saving failed", e);
            }
        } else {
            // 이미지가 없는 경우, 기존 파일 이름을 유지하기 위해
            // DB에서 기존 book 정보를 가져와서 fileName을 복사해야 합니다.
            Book existingBook = bookService.getBookById(book.getBookId());
            book.setFileName(existingBook.getFileName());
        }

        bookService.setUpdateBook(book);
        return "redirect:/books";
    }

    // 도서 삭제
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String getDeleteBookForm (Model model, @RequestParam("id") String bookId) {
        bookService.setDeleteBook(bookId);
        return "redirect:/books";
    }
}