inflearn

[인프런] 김영한의 스프링 입문 - MVC와 템플릿 엔진

hail2y 2024. 6. 25. 15:37

MVC - thymeleaf 템플릿 엔진

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

html의 파일 경로를 연 뒤 서버 없이 웹브라우저의 도메인에 그대로 입력해도 껍데기를 확인할 수 있다. 

그런데 템플릿 엔진으로서 동작하면 렌더링을 하여 th:text의 내용으로 치환한 html을 반환하게 된다.

정적 컨텐츠일 때는 변환하지 않고 그대로 반환한다. 

 

단축키

  • command + p: 파라미터 정보 확인 

 

API

1. 문자 전달

@ResponseBody

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

 

html의 head, body에서의 body가 아니라 http의 헤더부, 바디부를 말할 때의 바디를 의미한다. 

응답 바디부에 이 내용을 직접 넣어주는 부분.  뷰 없이 이 문자 그대로 클라이언트에 전달된다.

 

 

2. 객체 전달 - json 반환, 더 많이 사용(2020ver.)

@ResponseBody

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

@ResponseBody 애너테이션이 붙고 객체를 반환한다고 할 때 객체는 보통 json으로 반환하도록 되어 있다.

객체를 json으로 변환하는 역할을 하는 것은 대표적으로 Jackson 라이브러리, 구글의 gson. 

스프링은 기본적으로 전자(MappingJackson2HttpMessageConverter)를 사용한다. 

 

cf. Http Accept 헤더: 받고 싶은 포맷 정보가 담김

 

 

자바 빈 규약

  • 멤버변수의 접근 제어자를 private으로 설정하여 메서드를 통해 값을 설정하고 불러오는 방식을 취함. (-> getter, setter)