스프링 웹 개발 기초

이혜은·2022년 5월 6일
0

스프링 입문

목록 보기
1/1

정적 컨텐츠

html 파일을 서버에서 처리없이 그대로 반환하는 컨텐츠를 의미한다. 즉 프로그래밍을 할 수 없다.


⭐️ 스프링 컨테이너에서 hello-static에 관련된 컨트롤러를 우선으로 찾는다. 없으면 resources/static에서 hello-static html을 찾아서 웹브라우저로 보낸다.

MVC와 템플릿 엔진

- MVC: Model, View, Controller

1. Controller: 비즈니스 로직, 서버 등을 처리하는 기능을 포함하는 부분

@Controller
public class HelloController {

    @GetMapping("/hello-mvc")
    public String helloMvc(@RequestParam(value = "name", required = true) String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
}
  • @RequestParam(value = "name", required = true) String name : URL 쿼리 파라미터로 넣은 값을 받아오기 위해 사용하는 코드이다.   ```

2. View: 화면을 그리는 부분

resources/template/hello-template.html

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
    <p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
  • 이때 thymeleaf template 엔진을 사용한다.
  • 템플릿 엔진이 동작하면 컨트롤러가 넘겨준 key가 "name"인 value 값을 ${name}에 넣어서 화면에 출력된다.
  • 그저 html 파일 경로를 복사(서버가 없을때)하여 소스 코드를 조회할 경우 hello! empty가 보인다.

    View Template는 컨트롤러가 전달하는 model data를 이용하여 동적으로 화면을 구성할 수 있게 해준다. 뷰 템플릿 중 타임 리프가 있는데, 타임 리프html tag를 기반으로 하여 'th:' 속성을 이용하여 동적인 View를 제공하는 템플릿 엔진이다.

3. Model: 데이터와 비즈니스 로직을 관리하는 부분

API

MVC는 웹에 동적 HTML을 넘겨주는 반면, API 방식은 Data바로 웹에 넘겨주는 차이가 있다.

1. @ResponseBody 문자 반환

@Controller
public class HelloController {

    @GetMapping("/hello-string")
    @ResponseBody // HTTP의 body 부분에 직접 넣어주겠다는 뜻
    public String helloString(@RequestParam("name") String name) {
        return "hello" + name; 
    }
}
  • @ResponseBody를 사용하면 view resolver를 사용하지 않는다. 따라서 controller에서 return 하는 문자열을 갖고 해당하는 html을 매핑하지 않는다. 대신 HTTP의 BODY에 문자내용을 넣어서 직접 웹에 반환한다.

2. @ResponseBody 객체 반환

Data를 요구할 때 사용하는 방식이다.
@Controller
public class HelloController {

    // 데이터를 요구할때 유용하게 사용된다. -> API
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello; // 인스턴스(객체)를 넘긴다. -> JSON 방식으로 출력됨
    }

    static class Hello {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
result
{"name":"SPRING"}
  • @ResponseBody를 사용하고 인스턴스(객체)를 반환하면 객체가 JSON 형식으로 변환되어 웹에 출력된다.

3. @ResponseBody 사용 원리

  • @ResponseBody를 사용하면
    • HTTP BODY에 문자 내용을 넣어서 직접 반환
    • viewResolver 대신 HttpMessageConverter가 동작
    • 기본 문자는 StringHttpMessageConverter가 처리
    • 기본 객체는 MappingJackson2HttpMessageConverter가 처리(JSON으로 변환)

0개의 댓글