개(발)린이
Spring (게시글 조회수) 본문
이번시간은 쿠키를 이용해서 게시글 조회 시 조회 수가 올라가는 기능을 구현해본다.
먼저 BoardController 클래스이다.
@GetMapping("/detail/{boardCode}/{boardNo}")
public String boardDetail(@PathVariable("boardCode") int boardCode,
@PathVariable("boardNo") int boardNo,
@RequestParam(value = "cp", required = false, defaultValue = "1") int cp,
Model model,
HttpSession session,
HttpServletRequest req, HttpServletResponse resp
) {
@PathVariable은 URL 경로에 포함되어있는 값을 변수로 사용할 수 있게하는 역할
=> 자동으로 request scope에 등록됨으로써 jsp ${value} EL 작성 가능
또한 session scope에 있는 loginMember를 가져와야하는데 @ModelAttribute는 별도의 required 속성이 없기 때문에 필수적으로 저장되있어야 한다. 즉 session에 loginMember가 없으면 예외가 발생
그래서 HttpSession을 이용하였다.
BoardDetail detail = service.selectBoardDetail(boardNo);
// 게시글 상세 조회 서비스를 호출한다
if( detail != null) { // 상세 조회 성공 시
Member loginMember = (Member)session.getAttribute("loginMember");
int memberNo = 0;
if(loginMember != null) {
memberNo = loginMember.getMemberNo();
}
게시글 상세 조회가 성공한다면 세션에 loginMember를 가져온다.
memberNo는 미리 선언 해두고 만약에 로그인을 한 상태에서 조회 했을경우 loginMember 는
null이 아니기 때문에 loginMember의 MemberNo를 int memberNo에 대입해준다.
if( detail.getMemberNo() != memberNo) {
Cookie cookie = null;// 기존에 존재하던 쿠키를 저장하는 변수
Cookie[] cArr = req.getCookies();// 쿠키 얻어오기
if(cArr != null && cArr.length > 0) { // 얻어온 쿠키가 있을 경우
// 얻어온 쿠키 중 이름이 "readBoardNo" 가 있으면 얻어오기
for(Cookie c : cArr) {
if(c.getName().equals("readBoardNo")) {
cookie = c;
}
}
}
int result = 0;
if( cookie == null) { // 기존에 "readBoardNo" 이름의 쿠키가 없던 경우
cookie = new Cookie("readBoardNo", boardNo+"");
result = service.updateReadCount(boardNo);
} else { // 기존에 "readBoardNo" 이름의 쿠키가 있을 경우
// -> 쿠키에 저장된 값 뒤쪽에 현재 조회된 게시글 번호를 추가
// 단, 기존 쿠키값에 중복되는 번호가 없어야한다.
String[] temp = cookie.getValue().split("/");
// "readBoardNo" : "1/2/3/4/10/20/300/..."
List<String> list = Arrays.asList(temp); // 배열 -> List 변환
// List.indexOf(Object) :
// - List에서 Object와 일치하는 부분의 인덱스를 반환
// - 일치하는 부분이 없으면 -1 반환
if( list.indexOf(boardNo+"") == -1) { // 기존 값에 같은 글번호가 없다면 추가
cookie.setValue( cookie.getValue() + "/" + boardNo);
result = service.updateReadCount(boardNo); // 조회수 증가 서비스 호출
}
}
// 결과값 이용한 DB 동기화
if(result > 0) {
detail.setReadCount(detail.getReadCount() + 1); // 이미 조회된 데이터 DB 동기화
cookie.setPath(req.getContextPath());
cookie.setMaxAge(60 * 60 * 1);
resp.addCookie(cookie);
}
}
}
model.addAttribute("detail", detail);
return "board/boardDetail";
}
service와 serviceImpl 클래스에서 updateReadCount메소드를 보자
/** 조회수 증가 서비스
* @param boardNo
* @return result
*/
int updateReadCount(int boardNo);
-> service 인터페이스이다.
// 조회수 증가 서비스 구현
@Override
public int updateReadCount(int boardNo) {
return dao.updateReadCount(boardNo);
}
-> serviceImpl 클래스이다.
/** 조회수 증가 DAO
* @param boardNo
* @return
*/
public int updateReadCount(int boardNo) {
// TODO Auto-generated method stub
return sqlSession.update("boardMapper.updateReadCount", boardNo);
}
-> DAO이다.
마지막으로 mapper.xml 을 보자
<update id="updateReadCount">
UPDATE BOARD SET
READ_COUNT = READ_COUNT + 1
WHERE BOARD_NO = #{boardNo}
</update>
이제 실행해보자
492번 게시글 조회수가 0이다.
클릭해서 들어가보자.
조회수가 1 상승한것을 볼 수 있다.
'Spring' 카테고리의 다른 글
Spring(게시글 작성)-Controller (0) | 2023.05.12 |
---|---|
Spring(scheduling) (0) | 2023.05.11 |
Spring 게시판 3 (0) | 2023.05.02 |
Spring 게시판 테이블 (0) | 2023.05.01 |
Spring 게시판 2 (0) | 2023.05.01 |