티스토리 뷰
spring boot 의존성
maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
gradle(kotlin)
dependencies {
...
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
...
}
참고사이트
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
thymeleaf 문법
<input type="text" name="userName" value="James Carrot" th:value="${user.name}" />
value와 th:value가 있는걸 볼 수 있습니다. 이는 thymeleaf의 특징으로 정적화면을 구성할 때 value에 있는 James Carrot을 표시합니다. 이는 디자이너와 개발자 사이의 user.name에 해당하는 값을 렌더링 하기 전 디자인을 볼 수 있는 좋은 방법이 됩니다.
thymeleaf Filter
private boolean process(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
// This prevents triggering engine executions for resource URLs
if (request.getRequestURI().startsWith("/css") ||
request.getRequestURI().startsWith("/images") ||
request.getRequestURI().startsWith("/favicon")) {
return false;
}
/*
* Query controller/URL mapping and obtain the controller
* that will process the request. If no controller is available,
* return false and let other filters/servlets process the request.
*/
IGTVGController controller = this.application.resolveControllerForRequest(request);
if (controller == null) {
return false;
}
/*
* Obtain the TemplateEngine instance.
*/
ITemplateEngine templateEngine = this.application.getTemplateEngine();
/*
* Write the response headers
*/
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
/*
* Execute the controller and process view template,
* writing the results to the response writer.
*/
controller.process(
request, response, this.servletContext, templateEngine);
return true;
} catch (Exception e) {
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (final IOException ignored) {
// Just ignore this
}
throw new ServletException(e);
}
}
Thymeleaf Configuration
public class GTVGApplication {
...
private final TemplateEngine templateEngine;
...
public GTVGApplication(final ServletContext servletContext) {
super();
ServletContextTemplateResolver templateResolver =
new ServletContextTemplateResolver(servletContext);
// HTML is the default mode, but we set it anyway for better understanding of code
templateResolver.setTemplateMode(TemplateMode.HTML);
// This will convert "home" to "/WEB-INF/templates/home.html"
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// Template cache TTL=1h. If not set, entries would be cached until expelled
templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
// Cache is set to true by default. Set to false if you want templates to
// be automatically updated when modified.
templateResolver.setCacheable(true);
this.templateEngine = new TemplateEngine();
this.templateEngine.setTemplateResolver(templateResolver);
...
}
}
templateResolver.setPrefix, templateResolver.setSuffix 부분이 있어서 controller에서 return 할때 파일명만 적어주어도 알아서 경로에 있는 html파일을 클라이언트에게 제공해줍니다.
multi-language
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
브라우저는 이해할수 없는 속성은 무시합니다. th:text 부분은 thymeleaf 에서 사용하는 속성으로 HTML5 사양에서는 허용되지 않습니다. spring boot에서 올바르에 thymeleaf를 사용하기 위해서는 아래 코드를 추가해주어야 합니다.
<html xmlns:th="http://www.thymeleaf.org">
WebContext
Template에서 variable, request, session, application attribute를 가져오는데 필요한 몇가지 특수 표현식이 있습니다.
- ${x}xThymeleaf 컨텍스트 또는 요청 속성 으로 저장된 변수를 반환 합니다 .
- ${param.x}라는 요청 매개 변수 를 반환합니다 x(다중 값일 수 있음).
- ${session.x}라는 세션 속성 을 반환합니다 x.
- ${application.x}라는 서블릿 컨텍스트 속성 을 반환합니다 x.
표준 표현 문법 (Standard Expression Syntax)
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
<p>Today is: <span th:text="${today}">13 february 2011</span></p>
- Simple expressions:
- Variable Expressions: ${...}
- Selection Variable Expressions: *{...}
- Message Expressions: #{...}
- Link URL Expressions: @{...}
- Fragment Expressions: ~{...}
- Literals
- Text literals: 'one text', 'Another one!',…
- Number literals: 0, 34, 3.0, 12.3,…
- Boolean literals: true, false
- Null literal: null
- Literal tokens: one, sometext, main,…
- Text operations:
- String concatenation: +
- Literal substitutions: |The name is ${name}|
- Arithmetic operations:
- Binary operators: +, -, *, /, %
- Minus sign (unary operator): -
- Boolean operations:
- Binary operators: and, or
- Boolean negation (unary operator): !, not
- Comparisons and equality:
- Comparators: >, <, >=, <= (gt, lt, ge, le)
- Equality operators: ==, != (eq, ne)
- Conditional operators:
- If-then: (if) ? (then)
- If-then-else: (if) ? (then) : (else)
- Default: (value) ?: (defaultvalue)
- Special tokens:
- No-Operation: _
표현 기본객체(Expression Basic Objects)
- #ctx: the context object.
- #vars: the context variables.
- #locale: the context locale.
- #request: (only in Web Contexts) the HttpServletRequest object.
- #response: (only in Web Contexts) the HttpServletResponse object.
- #session: (only in Web Contexts) the HttpSession object.
- #servletContext: (only in Web Contexts) the ServletContext object.
So we can do this:
Established locale country: <span th:text="${#locale.country}">US</span>.
You can read the full reference of these objects in Appendix A.
표준 URL 문법
thymeleaf에서는 @{...} 이라는 link expression을 통해 URL을 쉽게 생성하는 방법을 제공합니다.
1. absolute URL
<a th:href="@{http://www.thymeleaf/documentation.html}">
2. context-relative url
가장 많이 사용하는 url 방법으로 접속한 사이트의 다른 경로로 이동할때 사용합니다.
<a th:href="@{/order/list}">
3. 파라미터 추가
<a th:href="@{/order/details(id=3)}">
<a th:href="@{/order/details(id=3,action='show_all')}">
<a th:href="@{/order/{id}/details(id=3,action='show_all')}">
위 코드는 아래와 같습니다.
<a href="/order/details?id=3">
<a href="/order/details?id=3&action=show_all">
<a href="/order/3/details?action=show_all">
Expression Utility Objects
Besides these basic objects, Thymeleaf will offer us a set of utility objects that will help us perform common tasks in our expressions.
- #execInfo: information about the template being processed.
- #messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
- #uris: methods for escaping parts of URLs/URIs
- #conversions: methods for executing the configured conversion service (if any).
- #dates: methods for java.util.Date objects: formatting, component extraction, etc.
- #calendars: analogous to #dates, but for java.util.Calendar objects.
- #numbers: methods for formatting numeric objects.
- #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
- #objects: methods for objects in general.
- #bools: methods for boolean evaluation.
- #arrays: methods for arrays.
- #lists: methods for lists.
- #sets: methods for sets.
- #maps: methods for maps.
- #aggregates: methods for creating aggregates on arrays or collections.
- #ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
You can check what functions are offered by each of these utility objects in the Appendix B.
object
th:object="${signUpForm}"
th:object에다가 객체를 지정해주면 form 채워주는 객체로 사용해줌
properties들은 *을 사용해서 지정할 수 있음
<input id="nickname" type="text" th:field="*{nickname}"/>
field는 input의 value를 값으로 쓰고 input parameter 이름으로도 사용함
Validation and Error Message
유효성 검사 및 에러메시지
thymeleaf에서는 유효성검사 메시지를 표시하기 위해 몇가지 도구를 제공합니다.
#fields객체의 두가지 기능으로 th:errors, th:errorclass 속성이 있습니다.
필드오류
<input type="text" th:field="*{datePlanted}" />
<p th:if="${#fields.hasErrors('datePlanted')}" th:errors="*{datePlanted}">Incorrect date</p>
#fields.hasErrors(...) 함수는 dataFlanted 매개변수의 유효성 검사 오류 여부를 bool로 알려줍니다.
th:errors는 지정된 선택자에 대한 모든 오류목록을 작성하는 특수 속성입니다.
오류기반 CSS 스타일링
th:errorclass
필드에 오류가 있는 경우 CSS class를 input등 입력양식에 설정하기 위해 위 속성을 제공합니다.
<input type="text" th:field="*{datePlanted}" class="small" th:errorclass="fieldError" />
error가 발행한 필드에 지정한 CSS class를 태그에 추가합니다.
렌더링 결과>
<input type="text" id="datePlanted" name="datePlanted" value="2013-01-01" class="small fieldError" />
확장프로그램
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
스프링 시큐리티를 타임리프에서 편하게 사용할수 있도록 해줌
HTML에 추가
xmlns:sec="http://www.thymleaf.org/extra/spring-security"
사용예
<span sec:authentication="name">Username</span>
sec:authorize="!isAuthenticated()"
'스프링' 카테고리의 다른 글
스프링부트(spring boot) javascript 의존성 관리 (0) | 2021.02.19 |
---|---|
JMeter 웹서버 부하테스트 (0) | 2021.02.05 |
@Valid 를 이용한 검증 및 Advice를 이용한 에러처리 (0) | 2020.06.10 |
JAVA SPRING 인터셉터 (Interceptor) (0) | 2018.07.26 |
JAVA SPRING 트랜잭션(Transaction) (0) | 2018.07.26 |