스프링 웹개발 기초 - MVC와 템플릿엔진

장서연·2022년 1월 1일
0

스프링 입문

목록 보기
7/25

과거에는... View 와 Controller를 한군데다 작성했었다. View 안에서 DB도 접근하고 컨트롤러 로직도 View에 있고... 하나의 View 파일안에 어마어마한 코드가 들어갈 수 밖에...

지금은, 따로 작성! 컨트롤러와 뷰를 쪼개는 게 기본!

뷰는 화면과 관련 일만하고, 컨트롤러는 비즈니스 로직만!

Contoller

HelloController.java

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

View

resources/template/hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:text="'안녕하세요!' + ${data}">안녕하세요 손님</p>
</body>
</html>

컨트롤러를 추가

HelloController.java

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

	// 파라미터를 넘겨주어야 한다
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name); // 파라미터를 모델이 담는다
        return "hello-template";
    }
}

검색창에,
http://localhost:8080/hello-mvc?name=spring

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="'안녕하세요!' + ${name}">안녕하세요 empty</p> // model 의 key 값이 name인것을 찾아 뿌려줌
</body>
</html>


정적일 때는 그냥 html 파일을 주었지만, 동적일 때는 변환후 웹 브라우저에게 전달한다.

0개의 댓글