본문 바로가기
SpringFramework/SpringBoot 기초

[SpringBoot] Spring 웹 개발 기초 - MVC

by 쭈봉이 2021. 12. 1.

정적 컨텐츠

resources > static에 있는 파일명을 그대로 가져옴

 

동적 컨텐츠

MVC : Model / View / Controller

템플릿 엔진 : Html을 동적으로 만드는 역할 (Thymeleaf)

 

Thymeleaf의 기능 중 파일을 우클릭해서 절대 경로를 가져올 수 있음

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(value = "name", required = false) String name, Model model){
        model.addAttribute("name",name);
        return "hello-template";
    }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>HTML5</title>
    <meta http-equiv="content-type" content="text/html" charset="utf-8">
</head>
<body>
<!--th:text는 Controller로부터 값을 가져왔을때, 태그 안에 있는 값은 값이 없을때 표기된다-->
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>
</body>
</html>

viewResolver 중요

 

API

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

@ResponseBody를 입력해주면 View를 내려주는게 아니라 문자열 그대로 떨굼

 

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

이런식으로 객체를 리턴하게 되면 아래와 같이 JSON으로 바로 떨궈준다

@ResponseBody 동작 방식

 

댓글