스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 (2)

Chan·2022년 3월 16일
0

Spring

목록 보기
2/9

<스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술>

  • 인프런 김영한님 강의 필기
  • 개발 환경 - Java 11, IntelliJ


스프링 웹개발 기초

  • 웹개발 방법 3가지
  1. 정적 컨텐츠 - 서버에서 아무것도 안하고 파일 그대로 웹 브라우저에 전달
  2. MVC와 템플릿 엔진 - 서버에서 html파일로 변형해서 웹 브라우저에 전달
  3. API - JSON 데이터 포맷으로 웹 브라우저 또는 클라이언트에 전달, 서버끼리 통신할 때도 사용

1. 정적 컨텐츠

  • 스프링 부트는 static을 찾아 정적컨텐츠 제공 기능을 자동 지원
  • resources/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>


<정적 컨텐츠 동작 과정>

  • 웹 브라우저에서 내장 톰켓 서버로 URL을 전달하면 Spring은 hello-static 관련 컨트롤러가 있는지 찾고, 없으면 static에서 정적 컨텐츠를 찾는다.
  • 찾으면 html 파일 그대로 웹 브라우저에 전달


2. MVC와 템플릿 엔진

  • MVC: Model, View, Controller (화면 뷰와 로직을 분리하기 위한 디자인 패턴)
    /////////////////////////////
  • Controller
  • java/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";
    }
}
  • View
  • resources/template/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

<MVC와 템플릿 엔진 동작 과정>

  • 웹 브라우저에서 내장 톰켓 서버로 URL을 전달하면 Spring은 hello-mvc 관련 컨트롤러가 있는지 찾는다.
  • GetMapping 찾으면 메서드 호출해서 return값 hello-template을 다시 받고, viewResolver가 같은 이름의 view를 찾아서 Thymeleaf 템플릿 엔진에 넘긴다.
  • 템플릿 엔진이 html로 렌더링(변환)해서 웹 브라우저에 넘긴다.

3. API

  • MVC가 별도의 View가 존재하고, html 파일을 변환하여 브라우저에게 전달하는 방식이라면,
    API는 브라우저에 데이터만 보내주고 화면을 만드는 건 브라우저가 담당하는 방식
  • API 방식의 주요 annotation
    @ResponseBody : html이 아닌 http의 통신 프로토콜이 header와 body로 나눠지는데,
    body에 이 내용을 직접 넣겠다는 의미다. 리턴되는 데이터가 클라이언트에게 그대로 전달된다. View가 별도로 존재하지 않는다.
  • API 방식에서는 return 타입으로 객체를 보내면 객체가 JSON으로 변환되어 브라우저에 전달된다.
    JSON: Key-Value 구조로 이루어진 문자열 데이터 포맷이다.
    //////////////////////
  • Controller
  • java/hello.hellospring/controller/HelloController.java
@Controller
public class HelloController {
    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
        return "hello " + name;     // 문자열 리턴
    }
    @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;
        }
    }
}

<API 동작 과정>

  • 웹 브라우저에서 내장 톰켓 서버로 URL을 전달하면 Spring은 hello-api 관련 컨트롤러가 있는지 찾는다.
  • GetMapping 찾음, @ResponseBody가 있으므로 http 응답의 body에 직접 넣어 그대로 전달
  • viewResolver 대신에 HttpMessageConverter가 받음
  • String - StringConverter 동작해서 문자열 형식으로 브라우저에 전달
  • 객체 - JsonConverter 동작해서 Json 형식으로 브라우저에 전달
profile
Backend Web Developer

0개의 댓글

관련 채용 정보