[Spring JPA ] - 댓글 작성 - 22

JEONG SUJIN·2023년 1월 10일
0

스프링부트 JPA

목록 보기
23/24

detail.jsp

<!--id값 주기-->
<textarea id="reply-content" class="form-control" rows="1"></textarea>
<button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>

board.js

let index = {
$("#btn-reply-save").on("click", ()=>{
			this.replySave();
		});
},
  
	replySave: function() {
		let data = {
			userId: $("#userId").val(),
			boardId: $("#boardId").val(),
			content: $("#reply-content").val()
		};

		console.log(data);

		$.ajax({
			type: "POST",
			url: `/api/board/${data.boardId}/reply`,
			data: JSON.stringify(data),
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		}).done(function(resp) {
			alert("댓글 작성이 정상적으로 등록되었습니다.");
			location.href = `/board/${data.boardId}`;
		}).fail(function(error) {
			alert(JSON.stringify(error));
		});
	},

ReplyRepository.java

//인터페이스생성
public interface ReplyRepository extends JpaRepository<Reply,Integer> {

}

ReplySaveRequestDto.java

서비스단과 컨트롤러에 한번에 넘기기 위해 생성

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReplySaveRequestDto {
	private int userId; //유저아이디
	private int boardId; //보드아이디
	private String content; //댓글내용
}

BoardService.java

//생성자 주입
private final ReplyRepository replyRepository;
private final UserRepository userRepository;
//댓글 등록
	@Transactional
	public void replyForm(ReplySaveRequestDto replySaveRequestDto) {
		
		User user = userRepository.findById(replySaveRequestDto.getUserId()).orElseThrow(()->{
			return new IllegalArgumentException("댓글쓰기 실패: 유저Id를 찾을 수 없습니다.");
		});// 영속화 완료
		
		
		Board board = boardRepository.findById(replySaveRequestDto.getBoardId()).orElseThrow(()->{
			return new IllegalArgumentException("댓글쓰기 실패: 게시글Id를 찾을 수 없습니다.");
		});// 영속화 완료
		
		Reply reply = Reply.builder()
				.user(user)
				.board(board)
				.content(replySaveRequestDto.getContent())
				.build();
		
		replyRepository.save(reply);
	}
	

BoardApiController.java

@PostMapping("/api/board/{boardId}/reply")
	public ResponseDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto ){	
		boardService.replyForm(replySaveRequestDto);
		return new ResponseDto<Integer>(HttpStatus.OK.value(),1);
	}

detail.jsp

	<!-- 댓글 창 만들기 -->
	<div class="card">
		<form>
			<input type="hidden" id="userId" value="${principal.user.id}" /> <input
				type="hidden" id="boardId" value="${board.id}" />
			<div class="card-body">
				<textarea id="reply-content" class="form-control" rows="1"></textarea>
			</div>
			<div class="card-footer">
				<button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>
			</div>
		</form>
	</div>
	<br />

	<div class="card">
		<div class="card-header">댓글 리스트</div>
		<ul id="comment--box" class="list-group">
			<c:forEach var="reply" items="${board.reply}">
				<li id="comment--1"
					class="list-group-item d-flex justify-content-between">
					<div>${reply.content }</div>
					<div class="d-flex">
						<div class="">작성자 ${reply.user.username}</div>
						<button type="button" onClick="index.replyDelete(${board.id}, ${reply.id })" class="badge">삭제</button>
					</div>
				</li>
			</c:forEach>


		</ul>
	</div>
profile
기록하기

0개의 댓글