스프링 웹 기초

Haechan Kim·2022년 7월 5일
0

Spring

목록 보기
3/68
  1. 정적 컨텐츠
    templates 에 html 파일 넣어두면 (ex.html) localhost:8080/ex.html 에서 html 그대로 보임.

  2. MVC와 템플릿 엔진

  • MVC: Model, View, Controller
@Controller // 컨트롤러 어노테이션
public class HelloController {
    // Get은 http 메서드
    @GetMapping("hello") // 웹 어플리케이션에서 /hello 들어가면 이 메서드 실행
    public String hello(Model model) { // mvc에서의 그 모델. 스프링이 모델 만들어서 넣어줌
        model.addAttribute("data", "spring!!"); // 키, 값
        return "hello"; // 뷰 리졸버(viewResolver) templates 밑 hello.html 찾음
    }

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) { // param으로 name 받기, model 넘겨줌, 모델에 담으면 뷰에서 렌더링
        model.addAttribute("name", name); // 키, 값
        return "hello-template"; // templates 폴더에 hello-template.html 찾음
    }
}
  • Model addAttribute(String name, Object value)
    모델에 데이터 담을 때 사용
    value 객체를 name 이름으로 추가하고 view 에서 name으로 지정한 이름을 통해 value를 사용한다.

  • hello-template.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

  1. API
    템플릿 엔진이 화면을 렌더링 해 html 파일을 웹 브라우저에 넘겨줬다면 API는 데이터를 바로 전달. (json 으로)
@Controller // 컨트롤러 어노테이션
public class HelloController {
    
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello; // 문자 아닌 객체 넘김. json으로 반환
    }

    static class Hello{
        private String name;

        // 우클릭 - generate - getter and setter
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

0개의 댓글