사진처럼 Controller와 RestController를 구분하는 것을 볼 수 있다.
그러면서 문득 든 생각
"둘의 차이점은 뭐지..?"
그래서 둘의 차이점을 한 번 정리하려고 한다.
@GetMapping("/index")
public String index() {
return "index"; // "test.html" 파일을 반환
}
: 위 코드에서 "test"는 실제로 test.html 파일을 가리킨다. 브라우저가 이 파일을 요청하여 렌더링하게 된다.
@GetMapping("/test")
public String test() {
return "test"; // HTTP 응답 본문에 "test"라는 문자열이 포함됨
}
: 위 코드에서 "test"는 HTTP 응답의 본문으로 전달된다.. 클라이언트는 이 응답을 JSON, XML, 또는 단순 문자열로 받아볼 수 있다.
<script>
function test(){
$.ajax({
url: "/index",
type: "GET",
contentType : 'application/json; charset=utf-8',
data: {},
cache: false,
success: (data, status, xhr)=>{
//alert("success!!");
alert(JSON.stringify(data));
},
error: (data, status, xhr)=>{
alert("error!!");
alert(JSON.stringify(data));
}
});
}
</script>
위의 코드와 같이 ajax 호출하는 test 라는 function을 보자. 이 function에서는 url을 "/index" 경로로 설정했다. 이 같은 경우에는 Controller의 Path로 접근하게 되어서 return 되는 값이 index.html의 HTML 코드가 된다.
<script>
function test(){
$.ajax({
url: "/api/test",
type: "GET",
contentType : 'application/json; charset=utf-8',
data: {},
cache: false,
success: (data, status, xhr)=>{
//alert("success!!");
alert(JSON.stringify(data));
},
error: (data, status, xhr)=>{
alert("error!!");
alert(JSON.stringify(data));
}
});
}
</script>
반면 위의 코드의 경우에는 url을 "/api/index" 경로로 설정했다. 이 같은 경우에는 Controller가 아닌 RestController의 Path로 접근하게 되었기에 return 되는 값이 HTML 코드가 아닌 "test"라는 문자열을 받게 된다.