전체 방문자
오늘
어제
21종
종이의 코딩 공부방
21종
  • 분류 전체보기 (171)
    • JAVA (64)
    • Springboot (46)
      • 블로그만들기 (45)
    • Database (60)
      • Oracle (60)
    • 프로젝트 3 (CELOVER) (0)
    • 개발서버 구축 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

인기 글

최근 글

최근 댓글

hELLO · Designed By 정상우.
21종

종이의 코딩 공부방

Springboot/블로그만들기

[Springboot] 블로그 만들기 (38)_댓글 작성하기 (Dto사용)

2023. 12. 8. 20:20

ReplySaveRequestDto.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReplySaveRequestDto {
	private int userId;
	private int boardId;
	private String content;
}

 

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="2"></textarea>
        </div>
        <div class="card-footer">
            <button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>
        </div>
    </form>
</div>

 

BoardApiController.java

@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto) {

    boardService.댓글쓰기(replySaveRequestDto);
    return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); 
}

 

board.js

let index = {
	init: function() {
		$("#btn-reply-save").on("click", () => {
			this.replySave();
		});
	}
	, replySave: function() {
		let data = {
			userId: $("#userId").val(),
			boardId: $("#boardId").val(),
			content: $("#reply-content").val()
		};
		let boardId = $("#boardId").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("댓글 작성이 완료되었습니다.");
			console.log(resp)
			location.href = `/board/${data.boardId}`;
		}).fail(function(error) {
			alert(JSON.stringify(error));
		});
	}
}

index.init();

 

BoardService.java

@Service
public class BoardService {

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private BoardRepository boardRepository;
	
	@Autowired
	private ReplyRepository replyRepository;

	@Transactional
	public void 댓글쓰기(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);
	}
}

 

 


참고 유튜브 (메타코딩님 강의)

https://youtu.be/bJTO67M1d78?si=4k9uCNaAZNhMNeUQ

    'Springboot/블로그만들기' 카테고리의 다른 글
    • [Springboot] 블로그 만들기 (40)_ 회원가입, 게시글 삭제 문제 해결
    • [Springboot] 블로그 만들기 (39)_댓글 작성하기 (네이티브 쿼리 사용)
    • [Springboot] 블로그 만들기 (37)_댓글 작성하기
    • [Springboot] 블로그 만들기 (36)_무한참조 방지하기
    21종
    21종
    코딩 공부한 것 정리하려고 만든 블로그

    티스토리툴바