✅ 메인 페이지
🌟 페이징 처리 🌟
⭐ MainController
@GetMapping("/ROLE_GUEST")
public String mainPage(Model model, @RequestParam(defaultValue = "2") int page) {
userService.getUserAndAddModel(model); // 사용자 정보 담기
List<ProductDto> countries = travelProductService.findAllCountriesByCountryLike();
model.addAttribute("countries", countries); // 최근 뜨는 여행지 담기
Pagination pagination = getPagination();
Page<CountryDto> countriesExcept4 = countryService.findAllCountriesExcept4(page, 4);
pagination.setTotalCount(countryService.countAllCountries() - 4); // 총 개수 - 4
model.addAttribute("pagination", pagination); // 페이징 담기
model.addAttribute("countriesExcept4", countriesExcept4); // 최근 4개 여행지 제외 전체 여행지 가져오기
return "main/main";
}
- @RequestParam(defaultValue = "2") int page
- 주소에서 page라는 이름의 데이터를 받음
- 예) localhost:8080/ROLE_GUEST?page=2
- 현재는 기본 페이지가 2번째 페이지이지만 보통은 1번째 페이지를 사용
- Pagination pagination = getPagination();
- 화면 하단에 페이지를 적기 위해 사용
- 예) << 1 2 3 4 5 >>
⭐ CountryService
@Service
public class CountryService {
@Autowired
private CountryDao countryDao;
/**
* 최근 뜨는 여행지 제외 모든 여행지 가져오기 - 페이징 처리
*/
public Page<CountryDto> findAllCountriesExcept4(int page, int size) {
int start = (page - 1) * size;
List<CountryDto> productDtos = countryDao.findAllCountriesExcept4(start, size);
int total = countryDao.countAllContries();
return new PageImpl<>(productDtos, PageRequest.of(page -1, size), total);
}
}
- findAllcountriesExcept4(int page, int size)
- 인자로 페이지와 사이즈를 받음
- page번째 단의 데이터를 size만큼 가져온다.
⭐ CountryDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.choyoujin.dao.CountryDao">
<!-- 나라별 좋아요가 많은 순으로 상위 4개 제외 나라 가져오기-->
<select id="findAllCountriesExcept4" resultType="com.example.choyoujin.dto.CountryDto">
SELECT MAX(tp.id) AS id, c.id AS countryId, c.*, SUM(tp.like) AS totalLikes
FROM country c
LEFT JOIN travel_product tp ON c.id = tp.country_id
GROUP BY c.id
ORDER BY totalLikes DESC
LIMIT #{size}
OFFSET #{page}
</select>
</mapper>
- LIMIT #{size} - 가져오는 데이터 개수를 #{size} 개로 한정
- OFFSET #{page} - #{page} 번째 단의 데이터를 가져옴
⭐ Main.jsp
<!-- 페이징 처리 -->
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<c:forEach begin="1" end="${pagination.endPage}" varStatus="status">
<li class="page-item">
<a class="page-link" href="?page=${status.index}">${status.index}</a>
</li>
</c:forEach>
<li class="page-item">
<a class="page-link" href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>