티스토리 뷰

Spring

스프링 입문 강의 정리 #2

코딩하는 브레드 2023. 4. 11. 12:16

인프런 김영한 강사님의 '스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술' 듣고 정리한 내용입니다.

 

 

[무료] 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링 웹 애플리케이션 개발 전반을 빠르게 학습할 수 있습니다., - 강의 소개 | 인프런

www.inflearn.com

 

섹션 2. 스프링 웹 개발 기초

1.  정적 컨텐츠

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>

 

실행 결과

 

- 동작원리

➡️ Controller 없이 화면 찾아서 바로 처리

 

2. MVC와 템플릿 엔진

MVC (Model View Controller)

- View: 화면을 그리는데 집중

- Model, Controller: 비지니스 로직이나 내부적으로 처리하는 것에 집중

 

<thymeleaf 템플릿 엔진>

장점

  • html 그대로 사용하고 서버 없이 실행해도 확인 가능
  • 파일의 absolute path 복사해서 실행

 

HelloController.java

package com.example.hellospring.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;

@Controller
public class HelloController {

    @GetMapping("hello") // 웹 어플리케이션에서 '/hello'로 들어오면 이 메소드 호출
    public String hello(Model model) {
        model.addAttribute("data", "Hello~!");
        return "hello";
    }

    @GetMapping("hello-mvc") // 웹 어플리케이션에서 '/hello-mvc?name=spring!'으로 값을 전달해줘야 함
    public String helloMVC(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
}

 

hello-template.html

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

 

<p th:text="'hello ' + ${name}">hello! empty</p>

▶️ 서버 없이 실행 시: hello! empty

▶️ 서버로 실행 시: 'hello ' + ${name} 여기에 값이 치환되어 실행

 

${} ➡️ 모델의 값을 꺼내서 치환

 

실행 결과

- 동작원리

 

3. API

<@ResponseBody 문자 반환>

HelloController.java

package com.example.hellospring.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("hello") // 웹 어플리케이션에서 '/hello'로 들어오면 이 메소드 호출
    public String hello(Model model) {
        model.addAttribute("data", "Hello~!");
        return "hello";
    }

    @GetMapping("hello-mvc") // 웹 어플리케이션에서 '/hello-mvc?name=spring!'으로 값을 전달해줘야 함
    public String helloMVC(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }

    @GetMapping("hello-string")
    @ResponseBody // HTTP 프로토콜 Body부에 데이터를 내가 직접 넣어주겠다는 의미
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
    }
}

helloString 메소드 차이점 : View 없이 문자가 요청한 대로 클라이언트에게 그대로 전달 (페이스 소스 보기 하면 html 코드 X)

 

실행 결과

 

@ResponseBody

없다? ➡️ ViewResolver에 전달하여 맞는 템플릿을 찾음!

있다? ➡️ HTTP 응답에 데이터를 넣음!

 

<@ResponseBody 객체 반환>

HelloController.java

package com.example.hellospring.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("hello") // 웹 어플리케이션에서 '/hello'로 들어오면 이 메소드 호출
    public String hello(Model model) {
        model.addAttribute("data", "Hello~!");
        return "hello";
    }

    @GetMapping("hello-mvc") // 웹 어플리케이션에서 '/hello-mvc?name=spring!'으로 값을 전달해줘야 함
    public String helloMVC(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }

    @GetMapping("hello-string")
    @ResponseBody // HTTP 프로토콜 Body부에 데이터를 내가 직접 넣어주겠다는 의미
    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;
        }
    }
}

➡️ @ResponseBody 사용하고 객체를 반환하면 HTTP 응답에 JSON 형식으로 데이터 반환

 

- 동작원리

➡️ @ResponseBody 사용

➡️ ViewResolver 대신 HttpMessageConverter 동작

- 단순 문자열이다? ▶️ StringConverter

- 객체이다? ▶️ JsonConverter

'Spring' 카테고리의 다른 글

스프링 입문 강의 정리 #6  (0) 2023.05.22
스프링 입문 강의 정리 #5  (0) 2023.04.18
스프링 입문 강의 정리 #4  (0) 2023.04.18
스프링 입문 강의 정리 #3  (0) 2023.04.15
스프링 입문 강의 정리 #1  (0) 2023.04.11
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함