thymeleaf 模板引擎


1.創建模板解析器 Create Template Resolver  用來加載模板

1 // create template resolver
2 //創建模板解析器可以用Servlet上下文模板解析器ServletContextTemplateResolver或者類加載模板解析器ClassLoaderTemplateResolver
3 
4 ServletContextTemplateResolver  templateResolver = new ServletContextTemplateResolver();
5 ClassLoaderTemplateResolver  templateResolver = new ClassLoaderTemplateResolver();

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

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

如上所示,通過解析器創建模板節點,當使用Thymeleaf渲染名為“home”的模板的的時候,將,解析器將會自動加上前綴和后綴(擴展名)。

2.創建模板引擎 Create Template Engine

1 //Create Template Engine
2 TemplateEngine templateEngine = new TemplateEngine();
3 templateEngine.setTemplateResolver(templateResolver);  //設置模板解析器

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

3.創建模板文件 

模板文件放在'/WEB-INF/templates/'路徑下。要指定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”屬性的值是一個變量表達式,它將獲取變量“hellword”的值作為<span>標簽的文本顯示到頁面上。

4.創建模板上下文

為了輸出變量“helloworld”的值,我們需要創建模板上下文,將變量輸出到模板文件中。

//create servlet context
WebContext ctx = new WebContext(req,resp,this.getServletContext(),req.getLocale());
ctx.setVariable('helloword','hello thymeleaf,wellcome!')

5.執行模板引擎

執行模板引擎需要傳入模板名、上下文對象以及響應流。如下:

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

讓我們看看執行模板引擎后的結果:

 技術分享

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

 

 

最后的源碼

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());
    }
}

 

 

原文地址:http://www.mamicode.com/info-detail-1150559.html


免責聲明!

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



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