타임리프에서는 기본 객체를 쉽게 활용할 수 있도록 기능을 제공한다. 따라서 각 객체들이 제공하는 메서드를 알면 다양하게 활용할 수 있다.
타임리프에서 request 객체에 접근하려면 ${#request}
를 이용한다.
<span th:text="${#request}"></span>
그렇다면 request 객체에서 requestParameter를 꺼낼 수가 있지 않을까?
<span th:text="${#request.getParameter('paramName')}"></span>
타임리프에서 response 객체에 접근하려면 ${#response}
를 이용한다.
<span th:text="${#response}"></span>
response 객체를 활용할 수 있기 때문에 예제로 헤더를 가져오려면 아래와 같이 할 수 있다.
<span th:text="${#response.getHeaer('headerName')}"></span>
타임리프에서 session 객체에 접근하려면 ${#session}
를 이용한다.
<span th:text="${#session}"></span>
타임리프에서 servletContext 객체에 접근하려면 ${#servletContext}
를 이용한다.
<span th:text="${#servletContext}"></span>
타임리프에서 locale 객체에 접근하려면 ${#locale}
를 이용한다.
<span th:text="${#locale}"></span>
위와 같이 접근할 수도 있지만, 많이 사용하는 것에 대해서는 Thymeleaf에서 더욱 손쉽게 접근할 수 있도록 지원한다.
위의 기본 객체에서 파라미터를 꺼내오는 방법보다 ${param}
을 이용하여 더욱 편리하게 접근할 수 있도록 지원한다.
<span th:text="${param.paramName}"></span>
위의 기본 객체에서 세션을 꺼내오는 방법보다 ${session}
을 이용하여 더욱 편리하게 접근할 수 있도록 지원한다.
<span th:text="${session.sessionName}"></span>
스프링 빈을 직접 호출할 수 있는 기능도 지원한다. 예제를 위해 스프링 빈이 아래와 같이 등록되어 있다고 가정하자.
@Component
static class myBean{
public String greeting(String name){
return "How are you" + name;
}
}
이런 경우에 타임리프를 통해 빈 객체에 접근하여 호출할 수도 있다.
<span th:text="${@myBean.greeting('John')}"></span>
How are you John 이 출력된다.