레이블이 thymeleaf인 게시물을 표시합니다. 모든 게시물 표시
레이블이 thymeleaf인 게시물을 표시합니다. 모든 게시물 표시

2016년 11월 19일 토요일

Spring Boot 1.4.x 에서 Thymeleaf 3 사용하기

Spring boot 1.4.0.RELEASE 이후 Thymeleaf 3.0을 지원하게 되었다.

기존 프로젝트를 판올림하면서 기록해본다.

1.4.x 이후에도 Spring Boot는 Thymeleaf 2에 대해 default 선언을 하고 있다.

Spring Boot Docs에는 다음과 같이 Thymeleaf 3 적용방법을 안내하고 있다.

[Use Thymeleaf 3]


이 내용은 기본적으로 사용하는 Thymeleaf 3이 적용에 대해서 안내하고 있으며 추가적인 라이브러리 들에 대해서는 언급되어 있지 않다.

다음과 같이 pom.xml에 추가한다.

<properties>
    <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
</dependency>

기본으로 사용하는 thymeleaf-layout-direct의 경우 boot dependencies에는 1.x대 (thymeleaf 2이하 지원)으로 선언되어 있으나 위 선언을 하면 2.x대 (thymeleaf 3 지원)으로 버전 상속된다.

추가적으로 사용하는 라이브러리에 대해 다음가 같이 추가해주어야 한다.

Java 8을 사용하는 경우 thymeleaf-extras-java8time 을 선언해서 사용해야 하며

Spring Security를 사용하는 경우 thymeleaf-extras-springsecurity4 를 선언해야한다.
(둘다 기본 설정이 Thymeleaf 2 이하로 선언되어 있다.)

다음과 같이 추가한다.

<properties>
    <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
    <thymeleaf-extras-springsecurity4.version>3.0.1.RELEASE</thymeleaf-extras-springsecurity4.version>
    <thymeleaf-extras-java8time.version>3.0.0.RELEASE</thymeleaf-extras-java8time.version>
</dependency>


thymeleaf 3에서는 기존과 다르게 HTML, HTML5에 대해 모드 구분이 필요없어졌다. 하지만 spring은 아직 기본으로 HTML5를 설정하고 있어 이에 대한 warning을 제거하려면 다음과 같이 application.properties에 선언해준다. (꼭 해야할 필요는 없다.)
spring.thymeleaf.mode=HTML

2016년 9월 28일 수요일

thymeleaf 에서 spring security login 여부를 변수로 사용하기

spring security 정보를 thymeleaf 에서 사용하는 기본적인 방법은 다음과 같다.

thymeleaf-extras-springsecurity4 를 사용하고 다음과 같이 호출한다.
<div sec:authorize="hasRole('ROLE_ADMIN')">
    This content is only shown to administrators.
</div>
<div sec:authorize="hasRole('ROLE_USER')">
    This content is only shown to users.
</div>

이와 같이 사용하면 영역별로 처리하기 편하지만 영역을 나누기 싫은 경우가 있다.

이럴 때엔 thymeleaf의 변수로 사용하는 것이 편하다.

다음과 같이 사용이 가능하다.

<div th:with="isLogin = ${#authorization.expression('isAuthenticated()')}">
[[${isLogin}]]
    </div>

일반적으로 위와 같이 사용하면 아무 문제가 없다.
하지만 security가 적용되지 않은 요청 범위의 페이지(예를 들면 /error/...와 같은 에러 페이지)를 호출할 경우
Caused by: java.lang.IllegalArgumentException: Authentication object cannot be null
에러가 발생한다.

spring security를 통해 authorization이 생성되지 않은 상태에서 expression을 호출하기 때문인데 이를 방지하기 위해 아래처럼 선언하는 것이 좋다.

<div th:with="isLogin = ${#authorization.getAuthentication() != null and #authorization.expression('isAuthenticated()')}">
[[${isLogin}]]
</div>