Spring/스프링 입문

[Spring] 스프링 웹 개발 기초

Jong_seoung 2025. 3. 15. 20:45
반응형

정적 콘텐츠

정적 콘텐츠는 말그대로 html 그 자체를 웹에 띄워준다.

// 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>

http://localhost:8080/hello-static.html 로 들어가면 페이지를 확인할 수 있다.


MVC와 템플릿 엔진

MVC는 모델, 뷰, 컨트롤러를 합친 용어이다.

 

뷰는 화면을 그리는데 집중하고, 뷰나 컨트롤러는 비지니스 로직같은 것을 처리해야한다.

 

// Controller

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

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

API

@ResponseBody를 사용하고, 객체를 반환하면 객체가 JSON으로 반환됨

@Controller
public class HelloController {
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name, Model model) {
        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;
        }
    }
}
반응형