Thymeleaf模板引擎使用

 

什麼是Thymeleaf

Thymeleaf是一個Java庫。它是一個XML / XHTML / HTML5模板引擎,可以在模板文件上應用一組轉換,將程序產生的數據或者文本顯示到模板文件上。html

Thymeleaf依賴的jar

要使用Thymeleaf,須要在咱們的web應用的classpath路徑中引入相關的jar,以下:java

thymeleaf-2.1.3.RELEASE.jar
ognl-3.0.6.jar
javassist-3.16.1-GA.jar
unbescape-1.0.jar
servlet-api-2.5.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
log4j-1.2.15.jar
mail-1.4.jar
activation-1.1.jarweb

建立模板解析器

使用Thymeleaf的前提很是簡單,首先建立一個模板解析器,用來加載模板,以下:api

1 //Create Template Resolver
2 ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
3 //ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

建立模板解析器能夠用Servlet上下文模板解析器ServletContextTemplateResolver或者類加載模板解析器ClassLoaderTemplateResolver。建立模板解析器將指定咱們從Servlet上下文檢索模板文件做爲資源,並考慮應用程序的根路徑做爲資源的路徑。以下:ide

// XHTML is the default mode, but we will set it anyway for better understanding of code
templateResolver.setTemplateMode("XHTML");
// This will convert "home" to "/WEB-INF/templates/home.html"
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");

如上所示,經過解析器建立模板節點,當使用Thymeleaf渲染名爲「home」的模板的的時候,將,解析器將會自動加上前綴和後綴(擴展名)。網站

建立模板引擎

建立了模板解析器加載模板後,接下來須要建立一個模板引擎去作實際的處理工做,以下:ui

//Create Template Engine
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);

建立模板引擎很近單,只須要一個模板解析器實例。建立了關鍵的模板解析器和模板引擎以後,咱們就能夠建立模板頁面使用Thymeleafthis

建立模板

咱們的模板文件放在/WEB-INF/templates/路徑下。建立模板文件只須要指定Thymeleaf特定的DOCTYPE和命名空間。以下:spa

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello thymeleaf</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <p>
      <span th:text="#{home.welcome}">this is text will not be show</span>
    </p>
  </body>
</html>

 

如上圖所示,模板文件中還定義了一個「th:text」屬性,咱們認爲模板文件是有效的,由於咱們已經經過doctype聲明瞭Thymeleaf dtd,這個類庫裏面聲明瞭這個屬性。當這個模板被處理時,這個「th:text」屬性將被移除,模板文件將被替換成一個嚴格的標準的XHTML文件。code

模板文件中的th:text」屬性的值是一個變量表達式,它將獲取變量「hellword」的值做爲<span>標籤的文本顯示到頁面上。

建立模板上下文

爲了能顯示變量「hellword」的值,咱們需建立模板上下文,將變量輸出到模板文件中。以下圖:

//Create Servlet context
WebContext ctx = new WebContext(req, resp, this.getServletContext(), req.getLocale());
ctx.setVariable("helloword","hello thymeleaf,wellcome!");

執行模板引擎

萬事具有,只欠引擎沒有開火。如今咱們須要作的就是執行模板引擎,執行模板引擎須要傳入模板名、上下文對象以及響應流。以下:

//Executing template engine
templateEngine.process("home", ctx, resp.getWriter());

讓咱們看看執行模板引擎後的結果:

 

OK,如上所說,模板文件被替換成了標準的XHTML文件了。

 

更多瞭解請訪問官方網站http://www.thymeleaf.org/

 

附源碼:

 

public class thymeleafServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //Create Template Resolver
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        //ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        // XHTML is the default mode, but we will set it anyway for better understanding of code
        templateResolver.setTemplateMode("XHTML");
        // This will convert "home" to "/WEB-INF/templates/home.html"
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU
        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);
        //Create Template Engine
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        //Write the response headers
        resp.setContentType("text/html;charset=UTF-8");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        //Create Servlet context
        WebContext ctx = new WebContext(req, resp, this.getServletContext(), req.getLocale());
        ctx.setVariable("helloword","hello thymeleaf,wellcome!");
        
        //Executing template engine
        templateEngine.process("home", ctx, resp.getWriter());
    }
}
相關文章
相關標籤/搜索