백엔드(Back-End) 개발/SpringBoot
[SpringBoot] 2.3_API (@ResponseBody)
rabo93
2025. 2. 25. 14:06
- @ResponseBody 문자 반환
package hello.hello_spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.service.annotation.GetExchange;
@Controller
public class HelloController {
@GetMapping("hello-string")
@ResponseBody // Http 통신 프로토콜의 body부에 내가 직접 넣어주겠다는 뜻
public String helloString(@RequestParam("name") String name) {
return "hello " + name; // view페이지가 아닌 "hello string" 문자 그대로 넘어감
}
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello; //JSON방식으로 객체 반환
}
static class Hello {
private String name;
//getter, setter 단축키 : alt + insert키
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
@ResponseBody를 사용하면 뷰 리졸버를 사용하지 않음
대신에 HTTP BODY부에 문자 내용을 직접 반환
@ResponseBody를 사용하고 객체를 반환하면 객체가 JSON으로 변환됨
@ResponseBody를 사용
- HTTP의 BODY에 문자 내용을 직접 반환
- 'ViewResolver' 대신에 'HTTPMessageConverter'가 동작
- 기본 문자처리 : 'StringHttpMessageConverter'
- 기본 객체처리 : 'MappingJackson2HttpMessageConverter'