본문 바로가기
Java/spring

[스프링 입문] ch02 웹 개발 기초 (정적 컨텐츠, MVC와 템플릿 엔진, API)

by 유일리 2022. 5. 12.

1. 정적 컨텐츠

서버에서 따로 가공을 거치지 않고 파일을 웹 브라우저에 그대로 보내는 방식이다.

<동작 원리>

1. 스프링은 hello-spring으로 요청이 들어오면 관련 컨트롤러를 찾는다.

2. 없는 경우 정적 컨텐츠를 찾아 그대로 반환해준다.

 

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

resources->static->hello-static.html 파일을 생성한 후 http://localhost:8070/hello-static.html에서 확인한다.

 

 

 

 

 

2. MVC와 템플릿 엔진

Model, View, Controller

<동작 원리>

1. 웹 브라우저에서 hello-mvc를 넘기면 내장 톰켓 서버를 먼저 거친다.

2. 스프링 컨테이너에서 helloController는 mapping이 되있는 것을 확인하고 그 메서드를 호출한다.

3. Model 객체에 key는 name, value는 spring인 attribute를 추가하고 hello-template으로 반환한다.

4. viewResolver가 return의 string과 똑같은 hello-template을 찾아서 Tymeleaf 템플릿 엔진 처리로 넘긴다.

5. 템플릿 엔진이 렌더링해서 html을 변환 후 넘겨준다.

 

<HelloController.java>

package hello.hellospring.controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;


@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data","hello!!");
        return "hello";
    }

    @GetMapping("hello-mvc")
    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>

java->hello.hellospring->controller->HelloController 파일에 작성한다.

resources->templates->hello-template.html을 생성 후 작성한다.

 

http://localhost:8070/hello-mvc?name=spring!!!!!! 을 입력하여 접속한다.

 

 

 

 

 

3. API

JSON 형식으로 바꾸어 반환하며 view 없이 그대로 전달하는 방식이다.

<동작 원리>

1. 웹 브라우저에서 hello-api를 요청하면 내장 톰켓 서버를 거친다.

2. 스프링 컨테이너에서 helloController에 hello-api가 mapping되어 있는지 확인한다.

3. @ResponseBody가 있는 것을 확인하고 HTTP의 BODY에 문자 내용을 직접 반환하고 HttpMessageConverter가 동작한다.

4. 문자인 경우 StringConverter를 통해 그대로 전달되고, 객체인 경우 JsonConverter를 통해 json 형태로 전달한다.

package hello.hellospring.controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data","hello!!");
        return "hello";
    }

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

    @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;
        }
    }
}

@ResponseBody를 사용하면 viewReslver을 사용하지 않고 직접 반환한다.

name 파라미터를 입력해 실행해보면 json 형식으로 데이터가 출력된다.

 


인프런 강의) 김영한의 스프링 입문 <코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술>

댓글