[Spring 입문] 웹 개발 기초- 정적 컨텐츠, MVC 방식, API 방식

Sujung Shin·2022년 12월 21일
0
post-thumbnail

💡 스프링 웹 개발 기초

  • 웹 개발은 크게 3가지 part로 나뉜다.

    1. 정적 컨텐츠(index.html, css)
    : 서버에서 따로 조정할 필요 없이 파일→웹 브라우저를 그대로 '내려준다'.
    2. MVC와 템플릿 엔진(jsp, php)
    : html을 동적으로 서버에서 프로그래밍한 후, 웹 브라우저에 그대로 '내려준다'.
    : Model, View, Controller의 패턴으로 개발한다.
    3. API
    : json 이라는 데이터 구조 포맷으로 클라이언트에게 전달하는 방식
    : 서버끼리의 데이터 호출



💻 정적 컨텐츠

  • 서버에서 별도로 하는 것 없이 파일을 그대로 웹 브라우저에 전달해줌(프로그래밍이 아닌, 그대로 반환함)
  • 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>
  • localhost::8080/hello-static.html 웹 브라우저로 접속하여 확인 가능





💻 MVC와 템플릿 엔진

  • Model, View, Controller : MVC(역할 분담)
  • View : 화면을 그리는 데 모든 것을 집중하여야 함.
  • Model, Controller : 비즈니스 로직, 서버 뒷단에 관련된 것은 Controller에서 다 처리를 하고, 화면에 필요한 것을 담아 Model에게 전달하여 넘겨줌.
    • MVC 방식은 결국 View라는 템플릿을 찾아서, 템플릿 엔진을 통하여 화면을 렌더링한 후 html을 웹 브라우저에게 넘겨주는 방식 이다.

Controller

@Controller
public class HelloController{

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

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) {
        //외부에서 받아온 파라미터
        model.addAttribute("name", name);
        return "hello-template"; //hello-template가 반환값
    }

@RequestParam(value= "name", required = "...")에서 required의 default값이 true이므로, 기본적으로 값을 넘겨야 한다.

View

resources/templates/hello-template.html

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

localhost:8080/hello-mvc?name=spring!
에서 파라미터인 spring!값을 넘기면, Controller에서 name자리에 spring!이 들어가 model.attribute("name", name)에 의하여, model에 담긴다.
model에 담긴 spring!은 View자리로 넘어가 ${name}에 파라미터값을 전달받는다.



💻 API

  • @ResponseBody 문자 반환
    1) @ResponseBody를 사용하면 뷰 리졸버(viewResolver) 대신에, HttpMessageConverter가 동작한다.
    2) 반환 값이 객체면, MappingJackson2HttpMessageConverter가 json으로 처리하고 문자면 StringHttpMessageConverter가 동작한다.
    3) byte처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어있다.
@Controller
public class HelloController{

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

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) {
        //외부에서 받아온 파라미터
        model.addAttribute("name", name);
        return "hello-template"; //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;
        }
    }

여기서 잘 살펴보면 return hello;부분에서 처음으로 문자가 아닌 객체를 넘겼다. 이 경우 어떻게 될까?

이를 json 방식이라고 한다. {key: value} 구조로 이루어져있다.
과거에는 xml 방식으로 많이 쓰였으나(html을 열고 닫는), 아주 심플한 방식인 json 방식으로 채택이 되고 있다.

  • 객체를 반환하고, @ResponseBody 어노테이션 붙이기
profile
백문이불여일타

0개의 댓글

관련 채용 정보