BACKEND/스프링 Spring

뷰 템플릿 호출 3가지 방법

꾸준히개발하자 2023. 12. 17. 19:45
// 뷰템플릿 호출 3가지 
@Controller
public class ResponseViewController {


    // ModelAndView 로 반환
    @RequestMapping("/response-view-v1")
    public ModelAndView resModelAndViewV1(){
        ModelAndView mav = new ModelAndView("response/hello")
                .addObject("data","hello!");
        return mav;
    }

    // 리턴 타입 String , @ResponseBody , @RestControler로 하게되면 그냥 문자로 리턴됨
    @RequestMapping("/response-view-v2")
    public String resModelAndViewV2(Model model){ // String 반환시 Model 이 필요
        model.addAttribute("data","hello");
        return "response/hello";
    }

    @RequestMapping("/response-view-v2")
    public void resModelAndViewV3(Model model){ // String 반환시 Model 이 필요
        model.addAttribute("data","hello");
        // 스프링이 return 을 생략할 수 있게 도와준다
    }
}

 

View

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${data}">empty</p>

</body>
</html>

 

String을 반환하는 경우 - View or HTTP 메시지 @ResponseBody 가 없으면 response/hello 로 뷰 리졸버가 실행되어서 뷰를 찾고, 렌더링 한다. @ResponseBody 가 있으면 뷰 리졸버를 실행하지 않고, HTTP 메시지 바디에 직접 response/hello 라는 문자가 입력된다. 여기서는 뷰의 논리 이름인 response/hello 를 반환하면 다음 경로의 뷰 템플릿이 렌더링 되는 것을 확인할 수 있 다.

실행: templates/response/hello.html Void를 반환하는 경우 @Controller 를 사용하고,

HttpServletResponse , OutputStream(Writer) 같은 HTTP 메시지 바 디를 처리하는 파라미터가 없으면 요청 URL을 참고해서 논리 뷰 이름으로 사용 요청 URL: /response/hello 실행: templates/response/hello.html 참고로 이 방식은 명시성이 너무 떨어지고 이렇게 딱 맞는 경우도 많이 없어서, 권장하지 않는다.

 

HTTP 메시지 @ResponseBody , HttpEntity 를 사용하면, 뷰 템플릿을 사용하는 것이 아니라, HTTP 메시지 바디에 직접 응답 데이터를 출력할 수 있다. Thymeleaf 스프링 부트 설정 다음 라이브러리를 추가하면(이미 추가되어 있다.) build.gradle ``` `implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'` ```

 

스프링 부트가 자동으로 ThymeleafViewResolver 와 필요한 스프링 빈들을 등록한다. 그리고 다음 설정도 사용한 다. 이 설정은 기본 값 이기 때문에 변경이 필요할 때만 설정하면 된다. application.properties ``` spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html