
📌 김영한 선생님의 스프링 입문 강의 강의를 들으면서 공부한 내용을 정리한 게시물입니다.
웹 개발 방법은 크게 정적 컨텐츠, MVC와 템플릿 엔진, API의 3가지로 나뉜다.
MVC: Model, View, ControllerModel, View, Controller로 모듈화하여 처리한다.JSON 포맷으로 클라이언트에게 데이터를 전달해주는 방식이다.서버에서 따로 하는 일 없이, 파일 그대로 웹 브라우저에 내려주는 것이다.
main/resources/static/hello-static.html<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
</head>
<body>
정적 컨텐츠입니다.
</body>
</html>
run → localhost:8080/hello-static.html 접속

hello-static이라는 컨트롤러를 찾아보고, 있으면 그것을 실행해준다.hello-static이라는 이름을 가진 파일을 찾아서 반환한다.⭐ 먼저 해당 이름을 갖는 컨트롤러를 찾아보고, 없으면 정적 리소스 파일을 찾는다.
서버에서 HTML을 그대로 내려주지 않고, 프로그래밍해서 동적으로 내려주는 것이다.
main/hello.hellospring/controller/HelloController.java@Controller
public class HelloController {
...
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
main/resources/templates/hello-template.html<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
run → localhost:8080/hello-mvc 접속하면 다음과 같이 에러가 발생한다.

Required request parameter 'name' for method parameter type String is not present]
→ 간단하게 말하자면 필요한 파라미터인name이 없다는 뜻이다!
⇒localhost:8080/hello-mvc?name=[원하는 값]이렇게 접속하면 된다.
localhost:8080/hello-mvc?name=yeonju 접속
name에 yeonju라는 값을 넘겨주니까 hello yeonju가 출력되었다.
hello-mvc를 넘기면 내장 톰캣 서버를 거친다.hello-mvc 메소드를 호출해주고, 리턴해줄 때 name에 spring을 넣어서 스프링에게 넘겨준다.hello-template을 찾아서 thymeleaf에게 처리해달라고 넘긴다.(최근에는)
JSON포맷으로 데이터를 전달해주는 방식이다.
main/hello.hellospring/controller/HelloController.java@Controller
public class HelloController {
...
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "helllo " + name;
}
}
@ResponseBody를 사용하면 뷰 리졸버(viewResolver)를 사용하지 않는다.View라는 것이 없이, 데이터 자체가 넘어간다! → 소스 보기를 하면 html 태그 없이 데이터 자체만 있다.이렇게 데이터 자체만 넘길 때는 API를 잘 사용하지 않는다.
Run → localhost:8080/hello-string?name=spring 접속
💡 템플릿 엔진과는 달리, 문자 그대로 (내가 적은 그대로)가 넘어간다!
main/hello.hellospring/controller/HelloController.java@Controller
public class HelloController {
...
@GetMapping("hello-api")
@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;
}
}
}
run → localhost:8080/hello-api?name=spring으로 접속하면 json 형태로 나타나게 된다!

@ResponseBody를 사용한다.viewResolver 대신에 HttpMessageConverter가 동작한다.StringHttpMessageConverterMappingJackson2HttpMessageConverterHttpMessageConverter가 기본으로 등록되어 있다.HTTP Accept 헤더와 서버의 컨트롤러 반환 타입 정보를 조합해서 HttpMessageConverter가 선택된다.TIL 정리 ]@ResponseBody를 사용하여 뷰 리졸버를 사용하지 않고, HTTP의 BODY에 직접 반환한다.