추가한 코드
Springboot
- boardController - viewCount
- boardService - viewCountUp
vue
- borad.vue (조회수 증가를 위한 통신)
- vue-cookies 설치 (npm install vue-cookies)
조회수 중복 방지를 구현하기 위해 쿠키를 사용했다.
우선 vue-cookies를 설치하고 vue- main.js 또는 vue에 쿠키를 사용한다고 명시해두자
(main.js 는 전역으로 쿠키를 사용할 때.)
import VueCookies from "vue-cookies";
//쿠키를 사용한다.
Vue.use(VueCookies);
Home에서 board로 이동할 때 mounted로 조회수 증가 메소드와 해당 게시글을 가져오는 메소드를 실행
조회수 중복 방지를 수행하기 위한 쿠키의 이름은 "viewCookie", 값은 "[해당 글 번호]"로 지정했다.
쿠키는 로그아웃 시 제거 할 예정이라서 member Id는 넣지않는다.
Springboot - boardJpa
@GetMapping(value = "/viewCount/{bid}")
public void viewCount(@PathVariable int bid, HttpServletRequest request, HttpServletResponse response){
Cookie oldCookie = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("viewCookie")) {
oldCookie = cookie;
}
}
}
if (oldCookie != null) {
if (!oldCookie.getValue().contains("[" + bid + "]")) {
boardJpaService.viewCountUp(bid); //조회수 증가
oldCookie.setValue(oldCookie.getValue() + "_[" + bid + "]");
oldCookie.setPath("/");
oldCookie.setMaxAge(60 * 60 * 24);
response.addCookie(oldCookie);
}
} else {
boardJpaService.viewCountUp(bid); //조회수 증가
Cookie newCookie = new Cookie("viewCookie","[" + bid + "]");
newCookie.setPath("/");
newCookie.setMaxAge(60 * 60 * 12);
response.addCookie(newCookie);
}
}
httpServletRequest로 부터 클라이언트의 쿠키를 가져온다.
여기서 oldCookie 는 vue에서 넘어온 기존에 있는 쿠키를 의미한다.
for문을 통하여 viewCookie라는 이름의 쿠키가 있는지 확인하고, 있으면 oldCookie에 저장한다.
oldCookie가 not null이지만 해당 "[bid]" 를 가지고 있지 않다면?
해당 글 id를 괄호로 감싸서 oldCookie에 저장 후 httpServletResponse로 Vue로 전달한다.
만약 oldCookie값이 없다면?
해당 글 id를 괄호로 감싸서 새로운 쿠키 생성 후 httpServletResponse로 Vue로 전달한다.
글 세부 페이지로 이동하면 해당 board Id가 쿠키에 저장되고 조회수가 증가된다.
해당 쿠키가 만료되기 전까지 같은 글로 이동해도 조회수가 증가되지 않는다.
자세한 코드의 설명은 출처의 블로그에서 확인하자
출처
https://kyounghwan01.github.io/blog/Vue/vue/vue-cookies/
https://mighty96.github.io/til/view/
'Vue > Vue' 카테고리의 다른 글
로그아웃 2 (Springboot + Vue) (0) | 2022.01.23 |
---|---|
로그아웃 1 (Springboot + Vue) (0) | 2022.01.20 |
글 수정 & 삭제 2 (Springboot + Vue) (0) | 2022.01.15 |
글 수정 1 (springboot - vue) (0) | 2022.01.14 |
글 작성 (Springboot + Vue) (0) | 2022.01.13 |