250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 자바
- 프로그래밍
- 백엔드개발자
- 알고리즘
- 자바알고리즘
- 백엔드
- 자바의정석
- 프로세스
- 개발자
- 미라클모닝
- 코드업
- 프로그래머
- 자바개발자
- 코딩
- 리액트
- 운영체제
- 데이터베이스
- 프로그래머스
- 개발자일기
- Java
- db
- 국비지원
- 혼공컴운
- 소셜로그인구현
- SpringBoot
- Codeup
- 스프링부트
- 국비지원코딩
- React
- 자바스크립트
Archives
- Today
- Total
초코딩(chocoding)
[Project - 게시판 / spring boot] Board 좋아요 기능 구현 본문
728x90
아.......... 오늘 너무 힘들다.................
Likes Insert
// Likes Insert =====================================================
@ResponseBody
@PostMapping("/likesInsert/{board_id}/{useremail}")
public ResponseEntity<?> postLikesInsert(@PathVariable("board_id") int board_id, @PathVariable("useremail") String useremail) {
Board boardEntity = boardService.selectDetail(board_id);
if (boardEntity != null) {
LikesId likesId = new LikesId(board_id, useremail);
Likes existingLike = likesService.findById(likesId);
if (existingLike != null) {
// 이미 좋아요를 눌렀다면 삭제
boardEntity.setBoard_likes(boardEntity.getBoard_likes() - 1);
likesService.delete(existingLike);
boardService.save(boardEntity);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); // 클라이언트에게 좋아요 삭제 상태 반환
} else {
// 좋아요를 누르지 않았다면 추가
Likes newLike = new Likes();
newLike.setUseremail(useremail);
newLike.setBoard_id(board_id);
boardEntity.setBoard_likes(boardEntity.getBoard_likes() + 1);
likesService.save(newLike);
boardService.save(boardEntity);
return ResponseEntity.ok().build(); // 클라이언트에게 좋아요 추가 상태 반환
}
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Board not found");
}
}
<script>
function toggleLike(board_id, useremail) {
console.log(board_id, useremail);
let url = "/board/likesInsert/" + board_id + "/" + useremail;
axios.post(url)
.then(response => {
let likeCountElement = document.getElementById('likeCount');
let currentLikeCount = parseInt(likeCountElement.textContent);
if (response.status === 200) {
likeCountElement.textContent = currentLikeCount + 1; // 좋아요 추가
} else if (response.status === 204) {
likeCountElement.textContent = currentLikeCount - 1; // 좋아요 삭제
}
})
.catch(error => {
console.error('Error toggling like:', error);
});
}
</script>
<div>
<button id="likeButton" onclick="toggleLike(${requestScope.boardDetail.board_id}, '${sessionScope.loginUser.useremail}')">❤️👍</button>
<span id="likeCount">${requestScope.boardDetail.board_likes}</span>
</div>
....알아서들 보세요........
728x90