[SpringBoot + Java] 스프링 웹(Static, MVC, API)
들어가며
- 백앤드를 짜게 되면 그행 결과를 확인할 프론트가 필요하다.
- Spring 의 3가지 방식인 Static, MVC, API 에 대해 간략하게 알아 보도록 하겠다.
Static
- 바로 저번 시간에 진행한 것 중 "resource/static" 디렉토리에 html 파일을 추가 한 것을 기억 할 것이다.
- static 이란 말 그대로 "정적" 이라는 말로 서버에서 어떠한 가공도 없이 정적으로 웹에 내려주는 페이지 이다.
- 아래 코드를 "resource/static" 에 "hello-static.html" 파일을 추가 한 후 실행 해 보도록 하겠다.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>static example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
static ex
</body>
</html>

- 따로 서버가 페이지를 가공 하지 않고 static ex 라는 글자가 그대로 나오는 것을 확인 할 수 있다.
MVC & 템플릿
- 여기서 MVC 란 (Model, View, Controller) 의 약자이며 보통 이러한 구조로 작업을 하기 때문에 MVC 라는 이름으로 굳어 졌다.
- 위의 static 과는 다르게 서버가 웹을 가공하여 브라우저로 내려 준다.
- 또한 가공을 위한 parameter 를 브라우저로 부터 넘겨 받을 수 있는데 아래 코드에서 확인 할 수 있다.
- 우선 동일한 방법으로 "resource/templates" 아래 적당한 이름으로 html 파일을 생성 해 준다.
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hihi in MVC. ' + ${name}"> hello</p>
</body>
</html>
- 그 후 해당 html 파일을 조작 하기 위해 Controller 파일을 수정 해 준다.
- 당연히 return 에 들어가는 String 과 html 파일의 이름을 동일하게 설정 해 주어야 한다.
package com.example.springlearn.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;
@Controller
public class HelloController {
@GetMapping("helloForMvc")
public String helloMvc(@RequestParam("name") String name, Model model){
model.addAttribute("name", name); // hello-template.html 의 name 에 param 을 대입
return "hello-template";// templates/hello-template 에 리턴 해 주게 됨
}
}
- 위 코드를 살펴 보면
@RequestParam 을통해 name 이라는 이름의 파라미터를 입력 받는다.
그 후 return 을 통해 html 파일로 넘어 가 ${name} 에 파라미터를 치환 시킨다.
이후 브라우져로 html 파일을 반환 하기 전 viewResolver 가 적절한 템플릿으로 처리 하여 넘겨 준다.
순서로 처리 된다.
- 여기서 url 로 파라미터를 처리 하는 방법은 ?[파라미터 이름]="값" 을 뒤에 붙이면 되는데 예시를 보면 이해하기 쉽다.
"http://localhost:8080/helloForMvc?name=madlimeus?"

API(기본)
- 이전의 두 방식은 브라우저에 어떤 식으로든 html 을 넘겨 주었다면 API 방식은 좀 다르다.
API 방식은 http 의 response 의 Body 부에 return 에 있는 데이터를 직접 넣어 준다.
예시를 보며 이해 해 보겠다.
- Controller 를 수정 한 후 실행 해 보도록 하겠다.
package com.example.springlearn.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;
@Controller
public class HelloController {
@GetMapping("helloString")
@ResponseBody
public String helloString(@RequestParam("name") String name){
return "hello " + name;
}
}
- 코드를 풀어 설명해 보자면 다음과 같다.
파라미터로 name 을 받고 이를 "hello " 뒤에 붙여 반환 한다.
- 하지만 이 코드가 위 두방식과 다른 점은 @ResponseBody 가 붙었다는 점이다.
이게 붙지 않았을 때는 브라우저에게 넘길때 View Resolver 에게 넘겨 맞는 템플릿을 찾아 브라우저로 넘기게 된다.
하지만 @ResponseBody가 붙어 있을 때는 "httpMessageConverter" 를 통해 원하는 type으로 데이터를 넘기게 된다.
- 따라서 실행후 브라우저를 보면 이렇게 된다.

- 얼핏 봐선 비슷 할 수 있지만 f12로 넘어온 sources 를 확인 해 보면 다른점을 쉽게 찾아 낼 수 있을 것이다.


API(데이터 넘기기)
- 위에서 @ResponseBody를 통해 원하는 type 으로 데이터를 넘길 수 있다고 서술 하였다.
- 그렇다면 string이 아닌 다른 데이터도 넘길 수 있을 것이다.
- 테스트를 위해 Controller 를 수정 하였다.
package com.example.springlearn.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;
@Controller
public class HelloController {
@GetMapping("helloApi")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
Hello hello = new Hello();
hello.setName(name);
return hello;
}
static class Hello{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
}
- Hello 라는 data class 를 만들고 이 데이터를 return 하는 Controller 이다.

- 결과를 보면 Json 형으로 출력 됨을 볼 수 있다.
요즘은 거의 대부분 Json을 사용 하기 때문에 기본으로 Json 으로 제공 한다고 한다.