기존에 정적 페이지와 템플릿 엔진을 활용한 동적 페이지 반환하는 방법에 대해 알아보았었는데, 이번엔 API를 통한 String, Json 객체 반환하는 방법에 대해 알아보자.
컨트롤러에 @ResponseBody 어노테이션을 붙이면 HTTP의 BODY에 문자 내용을 직접 반환하거나, 객체를 반환할 수 있다.
아래 샘플 코드는 http://localhost/hello-string?{key}={value} 로 들어오는 요청을 처리하는 메서드이다. @ResponseBody 어노테이션이 붙어 있고 String을 반환하고 있다.
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
실행 결과
아래 샘플 코드는 http://localhost/hello-api?{key}={value} 로 들어오는 요청을 처리하는 메서드이다. Hello라는 클래스의 인스턴스를 활용하고 있으며, hello라는 객체를 반환하고 있다.
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello;
}
public static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
실행 결과
View Resolver
대신에 HttpMessageConverter
가 동작한다.StringHttpMessageConverter
MappingJackson2HttpMessageConverter