스프링 입문(6. MVC와 템플릿 엔진)

min seung moon·2021년 4월 19일
0

Spring입문

목록 보기
6/10

1. MVC와 템플릿 엔진

  • MVC(Model View Controller)

01. Controller

  • demo/src/main/java/hello/demo/controller/HelloController
package hello.demo.controller;

import org.springframework.stereotype.Controller;

@Controller
public class HelloController {
    //MVC 방식
    // WebApplication에서 /hello로 접근을 하면 아래에 밑에 메소드를 호출
    // Get은 get, post 방식 중 get 방식으로 url로 접근했을 때 호출
    @GetMapping("hello")
    public String hello(Model model) {
        // key,value로 설정
        model.addAttribute("data","spring!!");
        // template 중 hello라는 이름을 가진 template에 전달, 여기서는 hello.html
        // resources:templates/ +{ViewName}+ .html, viewname은 return 값
        return "hello";
    }

    @GetMapping("hello-mvc")
    // 기본적으로 required가 true이기 때문에 값을 넣어줘야 한다
    // value = "name", required = false로 하면 값을 넘겨주지 않아도 된다
    public String helloMvc(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
}

02. View

  • demo/src/main/resources/templates/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<!-- hello! empty는 서버 없이 그냥 html을 만들어서 볼때, html 마크업 할 때, 서버를 통해서 접근하면 th:text의 값으로 바뀐다 -->
<p th:text="'hello1 ' + ${name}">hello! empty</p>
</body>
</html>

03. 실행

profile
아직까지는 코린이!

0개의 댓글

관련 채용 정보