|
5 | 5 | import java.util.stream.Collectors; |
6 | 6 | import java.util.stream.IntStream; |
7 | 7 |
|
| 8 | +import org.springframework.beans.factory.annotation.Autowired; |
| 9 | +import org.springframework.data.domain.Page; |
| 10 | +import org.springframework.data.domain.PageRequest; |
| 11 | + |
8 | 12 | import org.springframework.stereotype.Controller; |
9 | 13 | import org.springframework.ui.Model; |
10 | 14 | import org.springframework.web.bind.annotation.RequestMapping; |
11 | 15 | import org.springframework.web.bind.annotation.RequestMethod; |
12 | 16 | import org.springframework.web.bind.annotation.RequestParam; |
13 | 17 |
|
14 | 18 | import com.baeldung.thymeleaf.model.Book; |
15 | | -import com.baeldung.thymeleaf.model.Page; |
16 | | -import com.baeldung.thymeleaf.utils.BookUtils; |
| 19 | +import com.baeldung.thymeleaf.service.BookService; |
17 | 20 |
|
18 | 21 | @Controller |
19 | 22 | public class BookController { |
20 | 23 |
|
21 | 24 | private static int currentPage = 1; |
22 | 25 | private static int pageSize = 5; |
23 | 26 |
|
| 27 | + @Autowired |
| 28 | + private BookService bookService; |
| 29 | + |
24 | 30 | @RequestMapping(value = "/listBooks", method = RequestMethod.GET) |
25 | 31 | public String listBooks(Model model, @RequestParam("page") Optional<Integer> page, @RequestParam("size") Optional<Integer> size) { |
26 | 32 | page.ifPresent(p -> currentPage = p); |
27 | 33 | size.ifPresent(s -> pageSize = s); |
28 | 34 |
|
29 | | - List<Book> books = BookUtils.buildBooks(); |
30 | | - Page<Book> bookPage = new Page<Book>(books, pageSize, currentPage); |
| 35 | + Page<Book> bookPage = bookService.findPaginated(PageRequest.of(currentPage - 1, pageSize)); |
31 | 36 |
|
32 | | - model.addAttribute("books", bookPage.getList()); |
33 | | - model.addAttribute("selectedPage", bookPage.getCurrentPage()); |
34 | | - model.addAttribute("pageSize", pageSize); |
| 37 | + model.addAttribute("bookPage", bookPage); |
35 | 38 |
|
36 | 39 | int totalPages = bookPage.getTotalPages(); |
37 | | - model.addAttribute("totalPages", totalPages); |
38 | | - |
39 | | - if (totalPages > 1) { |
| 40 | + if (totalPages > 0) { |
40 | 41 | List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages) |
41 | 42 | .boxed() |
42 | 43 | .collect(Collectors.toList()); |
|
0 commit comments