Thymeleaf模板引擎使用


 

什么是Thymeleaf

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

Thymeleaf依賴的jar

要使用Thymeleaf,需要在我們的web應用的classpath路徑中引入相關的jar,如下:

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.jar

創建模板解析器

使用Thymeleaf的前提非常簡單,首先創建一個模板解析器,用來加載模板,如下:

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

創建模板解析器可以用Servlet上下文模板解析器ServletContextTemplateResolver或者類加載模板解析器ClassLoaderTemplateResolver。創建模板解析器將指定我們從Servlet上下文檢索模板文件作為資源,並考慮應用程序的根路徑作為資源的路徑。如下:

// 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”的模板的的時候,將,解析器將會自動加上前綴和后綴(擴展名)。

創建模板引擎

創建了模板解析器加載模板后,接下來需要創建一個模板引擎去做實際的處理工作,如下:

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

創建模板引擎很近單,只需要一個模板解析器實例。創建了關鍵的模板解析器和模板引擎之后,我們就可以創建模板頁面使用Thymeleaf

創建模板

我們的模板文件放在/WEB-INF/templates/路徑下。創建模板文件只需要指定Thymeleaf特定的DOCTYPE和命名空間。如下:

<!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文件。

模板文件中的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());
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM