# 15.1 模板解析器

我们为百里香虚拟杂货店选择了一个叫做`ServletContextTemplateResolver`的`ITemplateResolver`实现。它允许我们像来自Servlet上下文的资源一样获取模版。

除了让我们能够通过实现`ITemplateResolver`创建我们自己的模版解析器，Thymeleaf包含了四种立即可用的实现：

* `org.thymeleaf.templateresolver.ClassLoaderTemplateResolver`，当作类加载器资源解析模版，就像：

  ```java
  return Thread.currentThread().getContextClassLoader().getResourceAsStream(template);
  ```
* `org.thymeleaf.templateresolver.FileTemplateResolver`，当作来自文件系统的文件解析模版，就像：

  ```java
  return new FileInputStream(new File(template));
  ```
* `org.thymeleaf.templateresolver.UrlTemplateResolver`，当作URL（甚至非本地的URL）解析模版，就像：

  ```java
  return (new URL(template)).openStream();
  ```
* `org.thymeleaf.templateresolver.StringTemplateResolver`，当作`String` （以`template`指定，或者是模版名）解析模版：

  ```java
  return new StringReader(templateName);
  ```

`ITemplateResolver`的所有预绑定的实现允许相同的一组配置参数。它包括：

* 前缀和后缀（和已经看到的一样）：

  ```java
  templateResolver.setPrefix("/WEB-INF/templates/");
  templateResolver.setSuffix(".html");
  ```
* 模版别名。他允许使用不直接等于文件名的模版名字。如果前缀/后缀和别名同时存在，别名会在前缀/后缀之前被应用：

  ```java
  templateResolver.addTemplateAlias("adminHome","profiles/admin/home");
  templateResolver.setTemplateAliases(aliasesMap);
  ```
* 读取模板时的编码：

  ```java
  templateResolver.setEncoding("UTF-8");
  ```
* 使用的模板模式：

  ```java
  // Default is HTML
  templateResolver.setTemplateMode("XML");
  ```
* 模板缓存的默认模式，以及定义指定模板是否可缓存的模式：

  ```java
  // Default is true
  templateResolver.setCacheable(false);
  templateResolver.getCacheablePatternSpec().addPattern("/users/*");
  ```
* 由这个模板解析器产生的模板缓存入口的存活时间（毫秒计）。如果没有设置，从缓存里移除一个入口的唯一方式将会是超过最大缓存量（最老的入口会被移除）。

  ```java
  // Default is no TTL (only cache size exceeded would remove entries)
  templateResolver.setCacheTTLMs(60000L);
  ```

```
Thymeleaf + Spring整合包提供了一个`SpringResourceTemplateResolver`实现。它使用所有的Spring基础设施来访问和读取应用里的资源，是Spring应用里推荐的实现。
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/thymeleaf/i.-using-thymeleaf/15-geng-duo-pei-zhi/15.1-template-resolvers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
