13. 쿠키를 이용한 조회수 증가

BoardController
@GetMapping("{boardCode:[0-9]+}/{boardNo:[0-9]+}")
public String boardDetail(
@PathVariable("boardCode") int boardCode,
@PathVariable("boardNo") int boardNo,
Model model,
RedirectAttributes ra,
@SessionAttribute(value="loginMember", required=false) Member loginMember,
HttpServletRequest req,
HttpServletResponse resp
) {
Map<String, Integer> map = new HashMap<>();
map.put("boardCode", boardCode);
map.put("boardNo", boardNo);
if(loginMember != null) {
map.put("memberNo", loginMember.getMemberNo());
}
Board board = service.selectOne(map);
String path = null;
if(board == null) {
path = "redirect:/board/" + boardCode;
ra.addFlashAttribute("message", "게시글이 존재하지 않습니다.");
} else {
if(loginMember == null ||
loginMember.getMemberNo() != board.getMemberNo()) {
Cookie[] cookies = req.getCookies();
Cookie c = null;
for(Cookie temp : cookies) {
if(temp.getName().equals("readBoardNo")) {
c = temp;
break;
}
}
int result = 0;
if(c == null) {
c = new Cookie("readBoardNo", "[" + boardNo + "]");
result = service.updateReadCount(boardNo);
} else {
if(c.getValue().indexOf("[" + boardNo + "]") == -1) {
c.setValue(c.getValue() + "[" + boardNo + "]" );
result = service.updateReadCount(boardNo);
}
}
if(result > 0) {
board.setReadCount(result);
c.setPath("/");
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextDayMidnight = now.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
long secondUntilNextDay = Duration.between(now, nextDayMidnight).getSeconds();
c.setMaxAge((int)secondUntilNextDay);
resp.addCookie(c);
}
}
path = "board/boardDetail";
model.addAttribute("board", board);
if( !board.getImageList().isEmpty() ) {
BoardImg thumbnail = null;
if(board.getImageList().get(0).getImgOrder() == 0) {
thumbnail = board.getImageList().get(0);
}
model.addAttribute("thumbnail", thumbnail);
model.addAttribute("start", thumbnail != null ? 1: 0);
}
}
return path;
}
BoardSeviceImpl
@Override
public int updateReadCount(int boardNo) {
int result = mapper.updateReadCount(boardNo);
if(result > 0) {
return mapper.selectReadCount(boardNo);
}
return -1;
}
board-mapper.xml
<update id="updateReadCount">
UPDATE "BOARD" SET
READ_COUNT = READ_COUNT +1
WHERE BOARD_NO = #{boardNo}
</update>
<select id="selectReadCount">
SELECT READ_COUNT
FROM "BOARD"
WHERE BOARD_NO = #{boardNo}
</select>


