더북(TheBook)

그루비 코드 조각들을 모두 모았지만 그루비식 독서 목록 애플리케이션을 완성하려면 작성해야 하는 그루비 클래스가 하나 더 남아 있다. 웹 요청을 처리하고 독서 목록을 웹 브라우저에 보여 줄 ReadingListController의 그루비 구현체를 작성해야 한다. 프로젝트의 루트에 ReadingListController.groovy 파일을 만들고 코드 5-5를 작성하자.

 

코드 5-5 독서 목록을 보여 주고 추가하라는 웹 요청을 처리하는 ReadingListController

@Controller
@RequestMapping(”/”)
class ReadingListController {
 
    String reader=“craig”
 
    @Autowired
    ReadingListRepository readingListRepository // ReadingListRepository 주입
 
    @RequestMapping(method=RequestMethod.GET)
    def readersBooks(Model model) {
        List<Book> readingList=readingListRepository.findByReader(reader) // 독서 목록 조회
        if (readingList) {
            model.addAttribute(“books”, readingList) // 모델에 추가
        }
        “readingList” // 뷰 이름 반환
    }
 
    @RequestMapping(method=RequestMethod.POST)
    def addToReadingList(Book book) {
        book.setReader(reader)
        readingListRepository.save(book) // 책 저장
        “redirect:/” // POST 후 리다이렉트
    }
 
}

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.