웹 인터페이스 만들기
애플리케이션의 도메인과 해당 도메인 객체를 데이터베이스에 영속화하는 리포지토리를 정의했으므로, 이제 웹 프론트엔드를 만드는 일만 남았다. 코드 2-6과 같은 스프링 MVC 컨트롤러로 애플리케이션의 HTTP 요청을 처리한다.
코드 2-6 독서 목록 애플리케이션 앞단에 위치하는 스프링 MVC 컨트롤러
package readinglist; import java.util.List; 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; @Controller @RequestMapping(”/”) public class ReadingListController { private static final String reader=“craig”; private ReadingListRepository readingListRepository; @Autowired public ReadingListController(ReadingListRepository readingListRepository) { this.readingListRepository=readingListRepository; } @RequestMapping(method=RequestMethod.GET) public String readersBooks(Model model) { List<Book> readingList=readingListRepository.findByReader(reader); if (readingList != null) { model.addAttribute(“books”, readingList); } return “readingList”; } @RequestMapping(method=RequestMethod.POST) public String addToReadingList(Book book) { book.setReader(reader); readingListRepository.save(book); return “redirect:/”; } }