Thymeleaf Servlet Hellow World示例

Thymeleaf 2模板與Thymeleaf 3幾乎100%兼容,因此只需在配置中進行一些修改即可。在這一小節中,我們將通過一個簡單的示例(Hello World程序),演示如何配置和使用Thymeleaf。

首先,打開Eclipse,創建一個Maven項目,如下所示 -

Thymeleaf

設置工作目錄(F:\worksp\thymeleaf),如下圖所示 -

Thymeleaf

選擇一個原型(Archetype),這裏選擇:maven-archetype-webapp,如下圖所示 -
Thymeleaf

創建成功後,完整的項目目錄結構如下 -

Thymeleaf

Hello World示例使用以下組件庫 -

  • Thymeleaf 3
  • Servlet 3

Servlet3使用註解配置。

下面分別來看看有關項目中的配置和代碼 -

文件:pom.xml -

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai</groupId>
    <artifactId>helloworld</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Thymeleaf helloworld Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- Provided dependencies -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency> 
        <!-- Compile dependencies -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.7.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
        <defaultGoal>compile</defaultGoal>
    </build>

</project>

文件:TemplateEngineUtil.java -

package com.yiibai.thymeleaf3.config;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import org.thymeleaf.TemplateEngine;

/**
 * Store and retrieves Thymeleaf TemplateEngine into the application servlet context.
 */
@WebListener
public class TemplateEngineUtil {

    private static final String TEMPLATE_ENGINE_ATTR = "com.yiibai.thymeleaf3.TemplateEngineInstance";

    public static void storeTemplateEngine(ServletContext context, TemplateEngine engine) {
        context.setAttribute(TEMPLATE_ENGINE_ATTR, engine);
    }

    public static TemplateEngine getTemplateEngine(ServletContext context) {
        return (TemplateEngine) context.getAttribute(TEMPLATE_ENGINE_ATTR);
    }

}

配置文件:ThymeleafConfig.java -

package com.yiibai.thymeleaf3.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Thymeleaf configuration.
 */
@WebListener
public class ThymeleafConfig implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        TemplateEngine engine = templateEngine(sce.getServletContext());
        TemplateEngineUtil.storeTemplateEngine(sce.getServletContext(), engine);
    }

    public void contextDestroyed(ServletContextEvent sce) {
    }

    private TemplateEngine templateEngine(ServletContext servletContext) {
        TemplateEngine engine = new TemplateEngine();

        engine.setTemplateResolver(templateResolver(servletContext));
        return engine;
    }

    private ITemplateResolver templateResolver(ServletContext servletContext) {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

}

Servlet入口文件:IndexServlet.java -

package com.yiibai.thymeleaf3.web;

import com.yiibai.thymeleaf3.config.TemplateEngineUtil;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;


@WebServlet("/")
public class IndexServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TemplateEngine engine = TemplateEngineUtil.getTemplateEngine(request.getServletContext());
        WebContext context = new WebContext(request, response, request.getServletContext());        
        response.setCharacterEncoding("utf-8");
        context.setVariable("recipient", "Yiibai");
        engine.process("index.html", context, response.getWriter());
    }

}

模板文件:index.html -

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Thymeleaf3 + Servlet3 示例</title>
    </head> 
    <body>
        <h1>Thymeleaf 3 + Servlet 3 示例</h1>
        <p>
            Hello <span th:text="${recipient}"></span>!
        </p>
    </body>
</html>

使用Maven構建和運行應用程序的最簡單方法是執行mvn tomcat7:run,或者如果按照本教程使用Eclipse創建Maven項目,那麼可通過右鍵項目名稱,選擇:Run As -> Maven install,構建安裝生成後再右鍵項目名稱,選擇:Run As -> Run On Server,並在瀏覽器中訪問URL: http://localhost:8080/helloworld ,得到以下結果 -

Thymeleaf

這樣,我們的第一個Thymeleaf入門應用就完成了~!