◽ Java language/Java

[Java - (8) ] ResponseEntity - 독립적인 RestFul API를 개발

ResponseEntity
  • 참고 : https://doublesprogramming.tistory.com/110 

  • 데이터 + http status code

  • Client 의 플랫폼에 구애받지 않는 독립적인 RestFul API를 개발하기 위해, 상태코드, HttpHeader, 응답메시지, 반환 데이터를 모두 지정해서 반환해주기 위해 사용하는 것이다.

  • RestController는 별도의 View를 제공하지 않는 형태로 서비스를 실행하기 때문에, 때로는 결과데이터가 예외적인 상황에서 문제가 발생할 수 있다. ResponseEntity는 개발자가 직접 결과 데이터와 HTTP 상태 코드를 직접 제어할 수 있는 클래스 개발자는 404나 500같은 HTTP 상태 코드를 전송하고 싶은 데이터와 함께 전송할수 있기 때문에 좀더 세밀한 제어가 필요한 경우 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RequestMapping(value="insertRest.do", method=RequestMethod.POST)
    public ResponseEntity<String> insertRest(@RequestBody ReplyVO vo, HttpSession session){
        ResponseEntity<String> entity = null;
        try {
            String userId = (String) session.getAttribute("userId");
            vo.setReplyer(userId);
            replyService.create(vo);
            // 댓글입력이 성공하면 성공메시지 저장
            entity = new ResponseEntity<String>("success", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            // 댓글입력이 실패하면 실패메시지 저장
            entity = new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        // 입력 처리 HTTP 상태 메시지 리턴
        return entity;
    }
 
Color Scripter

푸터바