Spring

[Spring] 스프링 웹 개발 기초 (스프링입문 / 인프런 김영한님 강의)

펭귄코기 2022. 10. 1. 13:04

웹 개발에는 3가지가 있다

1) 정적 컨텐츠 : html그냥 주는거(정적)

2) MVC와 템플릿 엔진 : html을 그냥 주는게 아닌 서버에서 변경해서(동적) MVC패턴으로 

3) API : JSON이라는 데이터 구조 포맷으로 클라이언트에게 데이터를 전달

 

정적컨텐츠

main -> 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>

 

http://localhost:8080/hello-static.html

 

1) 웹 브라우저에서 주소를 입력하기

2) 내장톰캣서버

3) 스프링컨테이너에 와서 컨트롤러를 찾아봄

4) 컨트롤러 없으면 resources 내부에 html 파일찾기

5) 웹브라우저에 그대로 출력

 

MVC와 템플릿 엔진

모델, 뷰, 컨트롤러 3가지로 나누어서 각자의 역할을 하게 한다

 

뷰 : 화면 단

모델, 컨트롤러 : 로직, 서버 단

 

main -> java -> 패키지 -> controller 패키지 -> HelloController.java

package hello.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-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }
}

 

main -> resources -> templates -> hello-template.html

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

 

http://localhost:8080/hello-mvc?name=spring!

 

1) 웹 브라우저에서 주소를 입력하기

2) 내장톰캣서버

3) 스프링컨테이너에 와서 컨트롤러를 찾아봄

4) HelloController 발견

5) hello-mvc 라는 주소를 찾아봄

6) @GetMapping("hello-mvc") 발견

7) RequestParam("name") 이니까 주소에 ?name=spring! 받음 즉 name에 spring! 이 담겼음

8) model.addAttribute에 키값 "name" 벨류값 name 해서 return hello-template로 보냄

10) viewResolver 에서 Thymeleaf 템플릿 엔진 처리를 11,12 과정으로 해줌

11) resources 내부에 hello-template.html을 찾아 들어가서 키값 name이랑 같은 ${name} 찾음

12) 벨류값 name 인 spring! 을 넣고 html을 변경함

13) 웹브라우저 출력

 

API

html이 아닌 문자 그대로 화면에 넘기는 방식 (잘사용은 안함)

@ResponseBody를 사용하면 viewResolver 를 사용하지 않는다

대신에 HTTP의 BODY에 문자 내용을 직접 반환 (HTML BODY TAG를 말하는게 아니다)

 

main -> java -> 패키지 -> controller 패키지 -> HelloController.java

package hello.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-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
    }
}

 

객체로 넘겨주기 JSON 방식

스프링 기본이 객체를 반환하고 @ResponseBody 라고 해놓으면

JSON으로 반환을 해버린다

 

main -> java -> 패키지 -> controller 패키지 -> HelloController.java

package hello.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-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;
        }
    }
}

 

http://localhost:8080/hello-api?name=spting!

 

1) 웹 브라우저에서 주소를 입력하기

2) 내장톰캣서버

3) 스프링컨테이너에 와서 컨트롤러를 찾아봄

4) HelloController 발견

5) hello-api 라는 주소를 찾아봄

6) @GetMapping("hello-api") 발견

7) 그런데 @ResponseBody라는 어노테이션을 발견

8) HTTP의 BODY에 문자내용을 직접 반환해줌

9) viewResolver 대신에 HttpMessageConverter가 동작함

10) 이때 들어온 값에 따라 처리가 다른데

기본 문자 처리 : StringHttpMessageConverter (기본 문자열로)

기본 객체 처리 : MappingJackson2HttpMessageConverter (JSON형태로)

여기서는 객체가 들어왔기에 JSON 형태로 바꿔서 반환한다

11) JSON형태로 반환된값을 웹브라우저로 출력

 

스프링에서는 byte처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있다

클라이언트 HTTP Accept 헤더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서

HttpMessageConverter가 선택된다