08_Spring_240424(수)_70일차(1) - ★BoardProject★ - 13. 게시판 - 조회수(쿠키) 증가

soowagger·2024년 4월 24일

8_Spring

목록 보기
28/38

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

BoardController

  • req, resp, 쿠키 시작~끝 구문 추가
// 상세 조회 요청 주소
// board/1/1990?cp=1
// board/2/1990?cp=2
@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 // 새로운 쿠키 만들어서 응답하기
				) {
	
	// @SessionAttribute(value="loginMember", required = false)
	// - @SessionAttribute   : session 에서 속성 값 얻어 오기
	// - value="loginMember" : 속성의 key 값 loginMember
	// - required = false    : 필수 X (없어도 오류 X)
	//   -> 해당 속성값이 없으면 null 반환		
	
	
	// 게시글 상세 조회 서비스 호출
	
	// 1) Map으로 전달할 파라미터 묶기
	Map<String, Integer> map = new HashMap<>();
	
	map.put("boardCode", boardCode);
	map.put("boardNo", boardNo);
	
	// (좋아요) 로그인 상태인 경우에만 memberNo 추가
	if(loginMember != null) {
		map.put("memberNo", loginMember.getMemberNo());
	}
	
	
	// 2) 서비스 호출
	Board board = service.selectOne(map);
	
	String path = null;
	
	// 조회 결과가 없는 경우
	if(board == null) {
		path = "redirect:/board/" + boardCode; // 목록 재요청
		ra.addFlashAttribute("message", "게시글이 존재하지 않습니다.");
		
	// 조회 결과가 있는 경우
	} else { 
		
		/* ************************ 쿠키를 이용한 조회수 증가 (시작) ************************ */
		
		// 1. 비회원 또는 로그인한 회원의 글이 아닌 경우
		//    (글쓴이를 뺀 다른 사람)
		
		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; // 조회수 증가 결과를 저장할 변수
			
			// "readBoardNo"가 쿠키에 없을 때
			if(c == null) {
				
				// 새 쿠키 생성 ("readBoardNo", [게시글 번호])
				c = new Cookie("readBoardNo", "[" + boardNo + "]");
				result = service.updateReadCount(boardNo);
				
			} else {
				// "readBoardNo"가 쿠키에 있을 때
				// "readBoardNo" : [2][30][400][2000][4000]
				
				// 현재 글을 처음 읽은 경우
				if(c.getValue().indexOf("[" + boardNo + "]") == -1) {
					
					// 해당 글 번호를 쿠키에 누적 + 서비스 호출
					c.setValue(c.getValue() + "[" + boardNo + "]" );
					result = service.updateReadCount(boardNo);
				}
			}
			
			// 조회수 증가 성공 / 조회 성공
			if(result > 0) {
				
				// 먼저 조회된 board의 readCount 값을
				// result 값으로 변환
				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"; // board/boardDetail.html로 forward
		
		// board - 게시글 일반 내용 + imageList + commentList
		model.addAttribute("board", board);
		
		
		// 조회된 이미지 목록(imageList)가 있을 경우
		if( !board.getImageList().isEmpty() ) {
			
			BoardImg thumbnail = null;
			
			// imageList의 0번 인덱스 == 가장 빠른 순서(imgOrder)
			
			// 이미지 목록의 첫번째 행이 순서 0 == 썸네일인 경우
			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) {
	
	// 1. 조회수 1 증가
	int result = mapper.updateReadCount(boardNo);
	
	// 2. 현재 조회수 조회
	if(result > 0) {
		
		return mapper.selectReadCount(boardNo);
		
	}
	
	
	return -1; // 실패한 경우 -1 반환
}

board-mapper.xml

<!-- 조회수 1 증가 -->
<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>

profile

0개의 댓글