T_era

View Template 방식 본문

Programing/Spring

View Template 방식

블스뜸 2025. 5. 7. 13:28

Spring Framework에서는 Thymeleaf, JSP 등의 템플릿 엔진을 활용하여 View Template을 작성할 수 있다. View Template은 서버에서 전달받은 데이터를 HTML 구조에 맞게 삽입하여 최종적으로 클라이언트에게 전송될 HTML 문서로 변환된다. 이를 통해 사용자에게 동적으로 생성된 웹 페이지를 제공한다.

View Template은 Model에 담긴 데이터를 참조하여 HTML 등의 결과물을 동적으로 생성하고 클라이언트에게 응답한다.

Spring Boot는 기본적으로 View Template 경로를 src/main/resources/templates로 설정한다.

build.gradle에 Thymeleaf 의존성을 추가하면 ThymeleafViewResolver와 필요한 Spring Bean들이 자동으로 등록된다. Spring Boot는 아래와 같은 기본 설정을 자동으로 등록한다.

Properties
 
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html  // 또는 .jsp

@Controller의 응답으로 String 반환 시

@ResponseBody 어노테이션이 없는 경우, Spring은 ViewResolver를 실행하여 반환된 String 값을 View 이름으로 해석하고 해당 View를 찾아 렌더링한다.

@Controller
public class ViewTemplateController {

    @RequestMapping("/response-view")
    public String responseView(Model model) {
        // key, value
        model.addAttribute("data", "sparta");

        return "thymeleaf-view"; // View 이름 반환
    }

}

위 Controller 메서드는 "thymeleaf-view"라는 View 이름을 반환하며, Spring은 설정된 ViewResolver를 통해 src/main/resources/templates/thymeleaf-view.html 파일을 찾아서 렌더링한다.

Thymeleaf 템플릿 예시 (thymeleaf-view.html):

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    <h1>Thymeleaf</h1>
    <h2 th:text="${data}"></h2>
</body>
</html>

반면, @ResponseBody 어노테이션이 메서드에 적용되면 반환되는 String 값은 HTTP Message Body에 직접 입력되어 클라이언트에게 전송된다.

반환 타입이 void인 경우

반환 타입이 void인 Controller 메서드는 일반적으로 잘 사용되지 않는다. @Controller와 함께 @ResponseBody, HttpServletResponse, OutputStream과 같은 HTTP Message Body를 처리하는 파라미터가 없다면, Spring은 @RequestMapping URL을 참고하여 View 이름으로 사용한다.

Java
 
@Controller
public class ViewTemplateController {

    // thymeleaf-view.html 과 Mapping된다.
    @RequestMapping("/thymeleaf-view")
    public void responseViewV2(Model model) {
        model.addAttribute("data", "sparta");
    }

}

위 예시에서 /thymeleaf-view URL로 요청이 들어오면, Spring은 "thymeleaf-view"를 View 이름으로 간주하고 src/main/resources/templates/thymeleaf-view.html 파일을 찾아 렌더링한다.

'Programing > Spring' 카테고리의 다른 글

Client <=> Server 호출 및 응답 요약  (0) 2025.05.07
HTTP Message Body 방식  (0) 2025.05.07
정적 리소스 응답 방식  (0) 2025.05.07
Server에서 Client로 Data를 전달하는 방법  (0) 2025.05.07
HTTPMessageConverter  (0) 2025.05.07