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