Thymeleaf/Thymeleaf - 기본기능

Thymeleaf - 기본객체

진이최고다 2023. 4. 2. 21:47

📘기본객체

타임리프(Thymeleaf)에서는 다양한 기본객체들이 제공된다.

  • #ctx : 컨텍스트 정보를 제공하는 객체로, HttpServletRequest, HttpServletResponse, HttpSession 등에 접근
  • #locale : 클라이언트의 로케일 정보를 제공
  • #request : HttpServletRequest 객체를 제공
  • #response : HttpServletResponse 객체를 제공
  • #session : HttpSession 객체를 제공
  • #servletContext : ServletContext 객체를 제공

이 외에도 다양한 기본객체들이 존재한다.

 

그런데 #requestHttpServletRequest 객체가 그대로 제공되기 때문에 데이터를 조회하려면

request.getParameter("data")처럼 불편하게 접근해야한다.

 

이런 점을 해결하기 위해 편의 객체도 제공한다.

  • HTTP요청 파라미터 접근 : param 예 ) ${param.paramData}
  • HTTP세션 접근 : session 예 ) ${session.sessionData}
  • 스프링 빈 접근 : @ 예 ) $ {@helloBean.hello('Spring!')}
주의💣
스프링 부트 3.0 스프링 부트 3.0 부터는 ${#request} , ${#response} , ${#session} , ${#servletContext} 를 지원하지 않는다. 스프링 부트 3.0이라면 직접 model 에 해당 객체를 추가해서 사용해야 한다.

📖예제

Controller (스프링 부트 3.0)

    @GetMapping("/basic-objects")
    public String basicObjects(Model model, HttpServletRequest request,
                               HttpServletResponse response, HttpSession session) {
        session.setAttribute("sessionData", "Hello Session");
        model.addAttribute("sessionData", "Hello Session");
        model.addAttribute("request", request);
        model.addAttribute("response", response);
        model.addAttribute("servletContext", request.getServletContext());
        return "basic/basic-objects";
    }

    @Component("helloBean")
    static class HelloBean {
        public String hello(String data) {
            return "Hello" + data;
        }
    }

 

ViewCode(스프링 부트 3.0)

<!DOCTYPE html>
<html xmlns:th="http//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>기본 객체 (Expression Basic Objects</h1>
<ul>
    <li>request = <span th:text ="${request}"></span></li>
    <li>response = <span th:text ="${response}"></span></li>
    <li>session = <span th:text = "${session}"></span></li>
    <li>servletContext = <span th:text ="${servletContext}"></span></li>
    <li>locale = <span th:text = "${#locale}"></span></li>
</ul>

<h1>편의 객체</h1>
<ul>
    <li>Request Parameter = <span th:text="${param.paramData}"></span></li>
    <li>Session = <span th:text = "${session.sessionData}"></span></li>
    <li>spring bean = <span th:text= "${@helloBean.hello('Spring!')}"></span></li>
</ul>
</body>
</html>


 

인프런 김영한님의 Sping강의 기반으로 공부한 것을 작성한 블로그입니다.
출처 : 인프런 -🔗 스프링 MVC 1편  by 우아한형제 김영한이사님