DEVELOP
article thumbnail

웹 개발 방식

  1. 정적 컨텐츠 : 고정된 파일을 그대로 전달
  2. MVC와 템플릿 엔진 : html을 서버에서 변형해서 전달
  3. API : 서버끼리 통신할 때 자주 사용 

MVC와 템플릿 엔진 

- 컨트롤러에서는 내부로직에 집중, 뷰에서는 화면을 그리는데 집중함 

# Get 방식으로 데이터 받아 사용하기

▽ 컨트롤러에 아래 코드 추가

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

▽ resources/templates/hello-template.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello-template</title>
    <meta http-equiv="Content-Type"content="text/html; charset=UTF-8"/>
</head>
<body>
<p th:text="'hello!' + ${name}">hello. empty</p>
</body>
</html>

- localhost:8080/hello-mvc?name= 설정해주어야함 

- 템플릿 엔진에서는 viewResolver에서 htrml 파일을 변환해서 웹 브라우저에게 전송

localhost:8080/hello-mvc?name=choi


API 방식

▽ 컨트롤러에 아래 코드 추가

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
        return "hello, " + name;
    }

- @ResponseBody를 사용하면 HTTP의 BODY에 문자 내용을 직접 반환

- viewResolver를 사용하지 않고, HttpMessageConverter가 동작 

- 소스보기 하면 html 태그 없이 내용만 그대로 보임 

- 기본 문자처리: StringHttpMessageConverter

http://localhost:8080/hello-string?name=choi

▽ 컨트롤러에 아래 코드 추가

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

- 기본 객체 처리 : MappingJackson2HttpMessageConverter 

- 객체 반환하면, 객체가 JSON 방식(key-value) 으로 변환됨 

http://localhost:8080/hello-api?name=choi

profile

DEVELOP

@JUNGY00N