Spring 정적 컨텐츠 기능과 동작 과정 | MVC | API

심삼진·2023년 5월 2일
0

Spring

목록 보기
2/12

정적 컨텐츠란 ?

서버를 거치지 않고 파일을 웹 브라우저에 그대로 내려주는 것




예시를 들어봅시다.

static 폴더에 hello-static.html 파일을 생성해 줍니다.

<!DOCTYPE HTML>
<html>
<head>
 <title>static content</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>

http://localhost:8080/hello-static.html 로 접속하면 다음과 같은 결과가 나옵니다.

static 폴더에 원하는 파일을 넣으면 정적 파일로 반환됩니다.

하지만 이 파일에 그 어떤 프로그래밍도 할 수 없습니다.



정적 컨텐츠 동작 과정

Reference : https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-bootfeatures.html#boot-features-spring-mvc-static-content





MVC와 템플릿 엔진

MVC : Model, View, Controller의 줄임말이다.



Controller

@Controller
public class HelloController {
 @GetMapping("hello-mvc")
 public String helloMvc(@RequestParam("name") String name, Model model) {
 model.addAttribute("name", name);
 return "hello-template";
 }
}

resources/template/hello-template.html

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body></html>

이렇게 코드를 작성한 후 실행해보면 다음과 같이 나옵니다.

@RequestParamname을 통해 Model이 담겨지기 때문입니다.

thymeleaf 템플릿은 주소창에 파일 경로로 이동해도 그대로 결과가 나옵니다.



MVC, 템플릿 엔진 동작 과정

viewResolver

  • View를 찾아주고 템플릿을 연결시키는 해결자
  • 변환한 html을 웹브라우저에 변환





API


@ResponseBody 문자 반환

@GetMapping("hello-string")
 @ResponseBody
 public String helloString(@RequestParam("name") String name) {
 return "hello " + name;
 }
  • @ResponseBody 를 사용하면 뷰 리졸버( viewResolver )를 사용 X
  • 대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG 아님)

@ResponseBody 객체 반환

@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;
 }
 }
}
  • @ResponseBody 를 사용하고, 객체를 반환하면 객체가 JSON으로 변환



@ResponseBody 사용 원리

  • HTTP의 BODY에 문자 내용을 직접 반환
  • viewResolver 대신에 HttpMessageConverter 가 동작
  • 기본 문자처리: StringHttpMessageConverter
  • 기본 객체처리: MappingJackson2HttpMessageConverter
  • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

객체로 넘겨주었다면 디폴트로 JSON 형식으로 만들어서 HTTP에 반환합니다.





학습중인 스프링 강의 : https://inf.run/pcut
스프링 실습 코드 저장소 : https://github.com/0pyaq0/Spring_Study.git

본 글은 2022년도에 작성한 기존 티스토리 블로그 글을 재업로드한 글입니다
기존 티스토리 블로그 : https://develop-about-leejin.tistory.com/

profile
주니어 백엔드 개발자

0개의 댓글