댓글작성시 Dto 사용

 

프로젝트가 거대할수록 데이터를 받을때 컨트롤러에서 dto를 만들어서 받는게 좋다.

 

 

 

[BoardApiController]

//댓글작성
@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replySave(@PathVariable int boardId, @RequestBody Reply reply, @AuthenticationPrincipal PrincipalDetail principal) { 
    boardService.댓글쓰기(principal.getUser(), boardId, reply);
    return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); //자바 오브젝트를 JSON으로 변환해서 리턴
}

 

Reply reply 처럼 모델을 객체로 받아서 쓰는건 좋은 방법은 아니다. 

 

@PathVariable int boardId, @RequestBody Reply reply, @AuthenticationPrincipal PrincipalDetail principal

boardId, reply, user 정보  세가지 정보들을 dto로 한번에 받아보자

 

 

 

 

 

dto 사용할 때

 

Dto를 만들어서 세가지 정보를 다 넣고 컨트롤러에서 한번에 받기 

 

 

[ReplySaveRequestDto]

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

 

 

[BoardApiController]

//댓글작성
@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto) { 
    boardService.댓글쓰기(replySaveRequestDto);
    return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); //자바 오브젝트를 JSON으로 변환해서 리턴
}

요한 데이터를 한번에 받고 boardService.댓글쓰기(replySaveRequestDto) 할때 한꺼번에 데이터를 넘겨준다

 

 

 

 

user 정보, boardId, reply  세가지 정보 뷰페이지에서 가져오기

 

 

 

 

[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-rely-save" class="btn btn-primary">등록</button></div>
  </form>
</div>

ajax로 비동기처리

 

 

[board.js]

replySave: function() {
    let data = {      // 한번에 받음
        userId: $("#userId").val(),
        boardId: $("#boardId").val(),
        content: $("#reply-content").val()
    };

    $.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));
    });

 

data를 url 주소 /api/board/${data.boardId}/reply  이동 →  BoardApiController

 

 

 

[BoardApiController]

//댓글작성
@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto) { 
    boardService.댓글쓰기(replySaveRequestDto);
    return new ResponseDto(HttpStatus.OK.value(), 1); //자바 오브젝트를 JSON으로 변환해서 리턴
}

 

 

 

[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);
}

 

user, board를 영속화 시켜서 reply 오브젝트에 만들어서 값을 넣고 replyRepository.save(reply); 저장

 

 

 

 

반응형
LIST

+ Recent posts