본문 바로가기

카테고리 없음

Spring Boot @Controller (ResponseEntity와 redirect:)

@Controller

  • View를 생성하거나 반환하는 컨트롤러를 정의할 때 사용
  • Controller는 RequestMapping 어노테이션과 함께 사용하며,
  • 기본적으로 return을 하게되면 ViewResolver를 통해 RequestDispacher가 발동된다.

@GetMapping("/resp/v1")
public String respV1() {
    return "home";
}

@GetMapping("/resp/v2")
public String respV2(Model model) {
    model.addAttribute("title", "제목1");
    return "main";
}

위에서 말한데로 home 을 return하게 되면, 나의 경우에는 기본설정을 jsp대신 mustache로

해두었기 때문에 ViewResolver가 발동하여 .../home.mustache로 가게된다.

 

Model은 간단하게 말하면 Request Scope 라고 보면된다.


@ResponseBody

@GetMapping("/resp/v3")
public @ResponseBody String respV3() {
    return "<h1>text/html 응답</h1>";
}

ResponseBody를 붙이면 @RestController와 같은 역할을 해서 MessageConverter를 탄다.

즉, 데이터를 리턴한다는 말이다.

 

@GetMapping("/resp/v4")
public @ResponseBody BoardRespDto respV4() {
    return new BoardRespDto(1, "제목1", "내용1");
}

오브젝트를 리턴하게 되면 Jackson이 발동해 json으로 데이터가 리턴 된다.

 


@ResponstEntity

  • 상태코드를 리턴하고 싶을 때 사용한다.

 

@GetMapping("/resp/v5")
public ResponseEntity<Void> respV5() {
    return ResponseEntity.badRequest().build();
}

상태 코드를 리턴하며, 위의 코드는 리턴 타입이 <Void> 이기 때문에 따로 Body를 리턴 못하지만,

@GetMapping("/resp/v6")
public ResponseEntity<String> respV6() {
    return ResponseEntity.ok().body("hello");
}

이런식으로 리턴타입을 <String>으로 해주었을 경우 따로 Body를 리턴 해줄 수 있다.

@GetMapping("/resp/v7")
public ResponseEntity<?> respV7() {
    BoardRespDto boardRespDto = new BoardRespDto(2, "제목2", "내용2");
    return ResponseEntity.ok().body(boardRespDto);
}

마찬가지로 오브젝트를 넘겨 주었을 경우 Jackson이 발동한다.

이를 통해 알 수 있는 것은 ResponseEntity<>를 리턴타입으로 붙일 경우

자동으로 @ResponseBody가 발동 한다는 것이다.


redirect:

@GetMapping("/resp/v8")
public String respV8() {
    return "redirect:/resp/v1";
}

@Controller를 붙이게 되면 제일 위에서 말한데로 ViewResolver를 통해 RequestDispacher가 발동되어야 한다.

 

하지만 위의 코드처럼 redirect: 를 붙이게 되면 SendRedirect가 발동하게 된다.