@RestController

jooog·2022년 4월 24일
0

스프링

목록 보기
22/26
post-thumbnail

📖 @RestController로 댓글기능 구현하기

게시판의 댓글을 Spring의 RestController로 구현해본다.

  //지정한 게시물의 모든 댓글 가져오기
    @GetMapping("/comments")
    public ResponseEntity<List<CommentDto>> list(Integer bno){
        List<CommentDto> list = null;

        try {
            list = service.getList(bno);
            System.out.println("list= "+list);
            return new ResponseEntity<List<CommentDto>>(list, HttpStatus.OK); //200
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<List<CommentDto>>(HttpStatus.BAD_REQUEST); //400
        }
    }

📖 ResponseEntity

Entity란 요청이나 응답시 전송할 대상을 의미한다.
ResponseEntity로 댓글 list Entity에 http 상태코드도 함께 포함시켜서 응답한다.

📖 @PathVariable

PathVariablecno(댓글번호)로 삭제할 댓글을 식별한다.

//댓글 삭제하기
    @DeleteMapping("comments/{cno}") //comments/1?bno=1000 댓글 번호로 삭제
    public ResponseEntity<String> remove(Integer bno,
                                         @PathVariable Integer cno,
                                         HttpSession session){

        String commenter = "asdf";

        try{
            int rowCnt = service.remove(cno,bno,commenter);
            
            if(rowCnt!=1)
                throw new Exception("delete failed");

           return new ResponseEntity<>("Delete_OK", HttpStatus.OK);


        } catch(Exception e){
            e.printStackTrace();
            return new ResponseEntity<>("Delete_Error", HttpStatus.BAD_REQUEST);
        }

    }

//댓글 등록하기
    @PostMapping("/comments") //ch4/comments?bno=1000 POST
    public ResponseEntity<String> write(@RequestBody CommentDto dto,
                                        Integer bno,
                                        HttpSession session) {
        String commenter = "asdf";
        dto.setCommenter(commenter);
        dto.setBno(bno);
        System.out.println("dto = " + dto);

        try {
            if(service.write(dto)!=1)
                throw new Exception("write_error");
            return new ResponseEntity<String>("write_ok", HttpStatus.OK);
        } catch(Exception e){
            e.printStackTrace();
            return new ResponseEntity<String>("write_error", HttpStatus.BAD_REQUEST);
        }
    }

댓글등록 POST 요청
JSON 형식으로 데이터를 전달한다.

요청을 보낼 때는 서버에서 데이터를 받을 수 있도록 JSON으로 설정해두어야 한다. 그러면 요청으로 보낸 JSONCommentDto 자바 객체로 잘 변환된 후 데이터 베이스에 추가된다.

데이터베이스에서 확인

📖 @PatchMapping

댓글 수정하기

 //댓글 수정하기
    @PatchMapping("/comments/{cno}")
    public ResponseEntity<String> modify(@PathVariable Integer cno,
                                         @RequestBody CommentDto dto) {
        String commenter = "asdf";
        dto.setCommenter(commenter);
        dto.setCno(cno);
        System.out.println("dto = " + dto);

        try {
            if(service.modify(dto)!=1)
                throw new Exception("modify_error");
            return new ResponseEntity<String>("modify_ok", HttpStatus.OK);
        } catch(Exception e){
            e.printStackTrace();
            return new ResponseEntity<String>("modify_error", HttpStatus.BAD_REQUEST);
        }
    }

업데이트 요청보내기

데이터베이스 확인

0개의 댓글