Home Spring MVC - HTTP 응답 기본 기능
Post
Cancel

Spring MVC - HTTP 응답 기본 기능

HTTP View Template 응답

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RequestMapping("/response-view-v1")
public ModelAndView responseView() {
  ModelAndView mav =
  new ModelAndView("response/hello")
    .addObject("data", "hello!");
  return mav;
}

@RequestMapping("/response-view-v2")
public String responseViewV2(Model model) {
  model.addAttribute("data", "hello");
  return "response/hello";
}

@RequestMapping("/response/hello")
public void responseViewV3(Model model) {
  model.addAttribute("data", "hello");
}

HTTP API, 메세지 바디에 값 응답

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@GetMapping("/response-body-string-v1")
public void responseBodyV1(HttpServletResponse resp) throws IOException {
  resp.getWriter().write("ok");
}

/**
 * HttpEntity, ResponseEntity(Http Status 추가)
 * @return
 */
@GetMapping("/response-body-string-v2")
public ResponseEntity<String> responseBodyV2() {
  return new ResponseEntity<>("ok", HttpStatus.OK);
}


@ResponseBody
@GetMapping("/response-body-string-v3")
public String responseBodyV3() {
  return "ok";
}

@GetMapping("/response-body-json-v1")
public ResponseEntity<HelloData> responseJsonV1() {
  HelloData helloData = new HelloData();
  helloData.setUsername("user");
  helloData.setAge(10);
  return new ResponseEntity<>(helloData, HttpStatus.OK);
}

@ResponseStatus(HttpStatus.OK)
@ResponseBody
@GetMapping("/response-body-json-v2")
public HelloData responseJsonV2() {
  HelloData helloData = new HelloData();
  helloData.setUsername("user");
  helloData.setAge(10);
  return helloData;
}

@Controller 대신에 @RestController 애노테이션을 사용하면 해당 컨트롤러에 모두 @ResponseBody가 적용되는 효과가 있음


참고

  • 스프링 MVC - 백엔드 웹 개발 핵심 기술(김영한)
This post is licensed under CC BY 4.0 by the author.