知識庫 / Spring / Spring MVC RSS 訂閱

Spring 模板引擎

Spring MVC
HongKong
11
02:24 PM · Dec 06 ,2025

1. 概述

Spring Web 框架基於 MVC(模型-視圖-控制器)模式構建,這使得在應用程序中更容易分離關注點。 這樣就允許使用不同的視圖技術,從成熟的 JSP 技術到各種模板引擎。

在本文中,我們將探討與 Spring 配合使用時可用的主要模板引擎、它們的配置以及使用示例。

2. Spring View Technologies

鑑於 Spring MVC 應用中的關注點得到清晰分離,從一種視圖技術切換到另一種技術主要取決於配置。

為了渲染每種視圖類型,我們需要定義一個 ViewResolver 豆,對應於每種技術。這意味着我們可以像通常返回 JSP 文件一樣,從 @Controller 映射方法中返回視圖名稱。

在後面的章節中,我們將探討傳統的技術,如 Java Server Pages,以及可以與 Spring 一起使用的主要模板引擎:ThymeleafGroovyFreeMarkerJade

對於每種技術,我們將探討標準 Spring 應用和使用 Spring Boot 構建的應用中所需的配置。

3. Java Server Pages

JSP 是 Java 應用程序中最流行的視圖技術之一,並且 Spring 支持它。用於渲染 JSP 文件時,常用的 ViewResolver Bean 是 InternalResourceViewResolver

@EnableWebMvc
@Configuration
public class ApplicationConfiguration implements WebMvcConfigurer {
    @Bean
    public ViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/views/");
        bean.setSuffix(".jsp");
        return bean;
    }
}

接下來,我們可以開始在 /WEB-INF/views 目錄下創建 JSP 文件:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
    <head>
        <meta http-equiv="Content-Type" 
          content="text/html; charset=ISO-8859-1">
        <title>User Registration</title>
    </head>
    <body>
        <form:form method="POST" modelAttribute="user">
            <form:label path="email">Email: </form:label>
            <form:input path="email" type="text"/>
            <form:label path="password">Password: </form:label>
            <form:input path="password" type="password" />
            <input type="submit" value="Submit" />
        </form:form>
    </body>
</html>

如果我們將這些文件添加到 Spring Boot應用程序中,則與其在 ApplicationConfiguration類中定義,不如在 application.properties文件中定義以下屬性:

spring.mvc.view.prefix: /WEB-INF/views/
spring.mvc.view.suffix: .jsp

基於這些特性,Spring Boot 將自動配置必要的 ViewResolver

4. Thymeleaf

Thymeleaf 是一個 Java 模板引擎,它可以處理 HTML、XML、文本、JavaScript 或 CSS 文件。與其它模板引擎不同,Thymeleaf 允許將模板用作原型,這意味着它們可以被視為靜態文件。

4.1. Maven 依賴

為了將 Thymeleaf 與 Spring 集成,我們需要添加 thymeleafthymeleaf-spring4 依賴:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>

如果我們的項目是基於 Spring 4 的,那麼我們就需要添加 thymeleaf-spring4

4.2. Spring 配置

接下來,我們需要添加需要 SpringTemplateEngine Bean 及其 TemplateResolver Bean 的配置,該 Bean 指定了視圖文件的位置和類型。

SpringResourceTemplateResolver 與 Spring 的資源解析機制集成:

@Configuration
@EnableWebMvc
public class ThymeleafConfiguration {
 
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(thymeleafTemplateResolver());
        return templateEngine;
    }

    @Bean
    public SpringResourceTemplateResolver thymeleafTemplateResolver() {
        SpringResourceTemplateResolver templateResolver 
          = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }
}

此外,我們需要一個類型為 ThymeleafViewResolverViewResolver Bean:

@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    return viewResolver;
}

4.3. Thymeleaf 模板

現在我們可以將 HTML 文件添加到 WEB-INF/views 目錄下:

<html>
    <head>
        <meta charset="ISO-8859-1" />
        <title>User Registration</title>
    </head>
    <body>
        <form action="#" th:action="@{/register}" 
          th:object="${user}" method="post">
            Email:<input type="text" th:field="*{email}" />
            Password:<input type="password" th:field="*{password}" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

Thymeleaf 模板與 HTML 模板的語法非常相似。

使用Thymeleaf 在 Spring 應用中提供的功能包括:

    • 支持定義表單行為
    • 將表單輸入綁定到數據模型
    • 對錶單輸入進行驗證
    • 顯示來自消息源的值
    • 渲染模板片段

您可以在我們的文章《Thymeleaf 在 Spring MVC 中使用》中瞭解更多有關使用Thymeleaf 模板的信息。

4.4. Thymeleaf 在 Spring Boot 中的使用

Spring Boot 將通過添加 spring-boot-starter-thymeleaf 依賴來提供對 Thymeleaf 的自動配置。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.5.6</version>
</dependency>

無需進行任何顯式配置。默認情況下,HTML文件應放置在 resources/templates 目錄下。

5. FreeMarker

FreeMarker 是由 Apache 軟件基金會 構建的基於 Java 的模板引擎。它可用於生成網頁,但也可生成源代碼、XML 文件、配置文件、電子郵件和其他基於文本的格式。

生成基於使用 FreeMarker 模板語言 編寫的模板文件。

5.1. Maven 依賴

為了開始使用我們項目中的模板,我們需要 freemarker 依賴:

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

對於 Spring 集成,我們還需要添加 spring-context-support 依賴項:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>

5.2. Spring 配置

FreeMarker 與 Spring MVC 集成時,需要定義一個 FreemarkerConfigurer Bean,該 Bean 指定模板文件的位置:

@Configuration
@EnableWebMvc
public class FreemarkerConfiguration {
 
    @Bean 
    public FreeMarkerConfigurer freemarkerConfig() { 
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); 
        freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/");
        return freeMarkerConfigurer; 
    }
}

接下來,我們需要定義一個合適的 ViewResolver Bean,類型為 FreeMarkerViewResolver

@Bean 
public FreeMarkerViewResolver freemarkerViewResolver() { 
    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); 
    resolver.setCache(true); 
    resolver.setPrefix(""); 
    resolver.setSuffix(".ftl"); 
    return resolver; 
}

5.3. FreeMarker 模板

我們可以使用 FreeMarkerWEB-INF/views 目錄下創建 HTML 模板:

<#import "/spring.ftl" as spring/>
<html>
    <head>
        <meta charset="ISO-8859-1" />
        <title>User Registration</title>
    </head>
    <body>
        <form action="register" method="post">
            <@spring.bind path="user" />
            Email: <@spring.formInput "user.email"/>
            Password: <@spring.formPasswordInput "user.password"/>
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

在上述示例中,我們已導入了一組由 Spring 定義的宏,用於與 FreeMarker 配合使用表單,包括將表單輸入綁定到數據模型。

此外,FreeMarker 模板語言 包含大量標籤、指令和表達式,用於處理集合、流程控制結構、邏輯運算符、格式化和解析字符串、數字以及許多其他功能。

5.4. FreeMarkerSpring Boot 中的使用

Spring Boot 應用中,我們可以通過使用 spring-boot-starter-freemarker 依賴項來簡化所需的配置:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>3.1.5</version>
</dependency>

此啓動器添加了必要的自動配置。我們只需要將我們的模板文件放在 resources/templates 文件夾中即可。

6. Groovy 語言

Spring MVC 視圖也可以使用 Groovy 標記模板引擎 生成。該引擎基於構建器語法,可用於生成任何文本格式。

6.1. Maven 依賴

需要將 <a href="https://mvnrepository.com/search?q=groovy-templates" rel="noopener"><em title="groovy-templates">groovy-templates</em></a> 依賴添加到我們的 <em title="pom.xml">pom.xml</em></em> 中:

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-templates</artifactId>
    <version>2.4.12</version>
</dependency>

6.2. Spring 配置

Markup Template Engine 集成到 Spring MVC 中,需要定義一個 GroovyMarkupConfigurer Bean 和一個類型為 GroovyMarkupViewResolverViewResolver

@Configuration
@EnableWebMvc
public class GroovyConfiguration {
 
    @Bean
    public GroovyMarkupConfigurer groovyMarkupConfigurer() {
        GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
        configurer.setResourceLoaderPath("/WEB-INF/views/");
        return configurer;
    }
    
    @Bean
    public GroovyMarkupViewResolver thymeleafViewResolver() {
        GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver();
        viewResolver.setSuffix(".tpl");
        return viewResolver;
    }
}

6.3. Groovy Markup 模板

模板使用 Groovy 語言編寫,具有以下特點:

    • 它們會被編譯成字節碼
    • 它們支持片段和佈局
    • 它們提供國際化支持
    • 渲染速度快

讓我們為我們的“用户註冊”表單創建 Groovy 模板,該模板包含數據綁定:

yieldUnescaped '<!DOCTYPE html>'                                                    
html(lang:'en') {                                                                   
    head {                                                                          
        meta('http-equiv':'"Content-Type" ' +
          'content="text/html; charset=utf-8"')      
        title('User Registration')                                                            
    }                                                                               
    body {                                                                          
        form (id:'userForm', action:'register', method:'post') {
            label (for:'email', 'Email')
            input (name:'email', type:'text', value:user.email?:'')
            label (for:'password', 'Password')
            input (name:'password', type:'password', value:user.password?:'')
            div (class:'form-actions') {
                input (type:'submit', value:'Submit')
            }                             
        }
    }                                                                               
}

6.4. 在 Spring Boot 中使用 Groovy 模板引擎

Spring Boot 包含對 Groovy 模板引擎的自動配置,通過包含 spring-boot-starter-groovy-templates 依賴即可實現。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-groovy-templates</artifactId>
    <version>2.5.6</version>
</dependency>

默認模板的位置是 /resources/templates

7. Jade4j

Jade4jPug 模板引擎(原名 Jade)的 Java 實現,用於生成 HTML 文件。

7.1. Maven 依賴

為了實現 Spring 集成,我們需要 spring-jade4j 依賴:

<dependency>
    <groupId>de.neuland-bfi</groupId>
    <artifactId>spring-jade4j</artifactId>
    <version>1.2.5</version>
</dependency>

7.2. Spring 配置

為了使用 Jade4j 與 Spring 結合,我們需要定義一個 SpringTemplateLoader Bean,該 Bean 配置模板的位置,以及一個 JadeConfiguration Bean:

@Configuration
@EnableWebMvc
public class JadeTemplateConfiguration {
 
    @Bean
    public SpringTemplateLoader templateLoader() {
        SpringTemplateLoader templateLoader 
          = new SpringTemplateLoader();
        templateLoader.setBasePath("/WEB-INF/views/");
        templateLoader.setSuffix(".jade");
        return templateLoader;
    }
 
    @Bean
    public JadeConfiguration jadeConfiguration() {
        JadeConfiguration configuration 
          = new JadeConfiguration();
        configuration.setCaching(false);
        configuration.setTemplateLoader(templateLoader());
        return configuration;
    }
}

接下來,我們需要標準的 ViewResolver Bean,在本例中是 JadeViewResolver 類型:

@Bean
public ViewResolver viewResolver() {
    JadeViewResolver viewResolver = new JadeViewResolver();
    viewResolver.setConfiguration(jadeConfiguration());
    return viewResolver;
}

7.3. Jade4j 模板

Jade4j 模板以易於使用的、對空白字符敏感的語法為特徵:

doctype html
html
  head
    title User Registration
  body
    form(action="register" method="post" )
      label(for="email") Email:
      input(type="text" name="email")
      label(for="password") Password:
      input(type="password" name="password")
      input(type="submit" value="Submit")

該項目還提供非常實用的交互式文檔,您可以在編寫模板的同時查看輸出結果。

Spring Boot 不提供 Jade4j 啓動器,因此在 Boot 項目中,我們需要添加與上述定義相同的 Spring 配置。

8. Java 模板引擎 (jte)

Java 模板引擎 (Java 模板引擎 (jte)) 是一款輕量級且快速的模板引擎,適用於 Java 和 Kotlin Web 應用程序。

8.1. Maven 依賴

要使用該模板引擎,請將其 依賴項添加到 `pom.xml</em/>:

<dependency>
    <groupId>gg.jte</groupId>
    <artifactId>jte</artifactId>
    <version>3.1.15</version>
</dependency>

此外,我們還可以安裝 jte IntelliJ 插件,以便在處理 jte 模板時獲得代碼提示和自動補全功能。

8.2. Spring 配置

此外,我們還需要定義一個配置類,用於指定渲染的文件類型。首先,我們需要通過定義 TemplateEngine Bean 來指定模板文件的位置:

@Configuration
@EnableWebMvc
class Config implements WebMvcConfigurer {
    @Bean
    TemplateEngine templateEngine(ServletContext context) {
        String root = context.getRealPath("/WEB-INF/views/");
        DirectoryCodeResolver codeResolver = new DirectoryCodeResolver(Path.of(root));
        String classesPath = context.getRealPath("/WEB-INF/classes/");
        return TemplateEngine.create(
          codeResolver, Path.of(classesPath), ContentType.Html, this.getClass().getClassLoader());
    }

    @Bean
    ViewResolver viewResolver(TemplateEngine templateEngine) {
        return (viewName, locale) -> (model, request, response) -> {
          templateEngine.render(
            viewName + ".jte",
            (Map<String, Object>) model,
            new PrintWriterOutput(response.getWriter()));
        };
    }

    // ...
}

在定義了 TemplateEngine Bean 後,我們還定義了 ViewResolver Bean。 ViewResolver Bean 指定了 “.jte” 作為視圖模板的後綴,並渲染模型數據。

8.3. JTE 模板

接下來,讓我們在 WEB-INF 目錄下創建一個 .jte 模板文件:

@import com.baeldung.spring.domain.Message
@param Message message

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Baeldung - Duke Page</title>
</head>
<body>
    <form action="/welcome" method="post">
        Name: <input type="text" name="text" value="${message.getName()}">
        Message: <input type="submit" value="${message.getText()}">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

.jte 模板採用 Java 導入樣式,並使用註解將模型注入到 HTML 模板中。這裏,我們導入一個名為 Message 的模型類。然後,我們創建一個表單,用於接受 nametext 作為輸入。

8.4. 在 Spring Boot 中使用 JTE

JTE 提供基於 Spring Boot 版本的 starter 依賴項。要使用 JTE 與 Spring Boot 版本 3 配合使用,我們需要將 <a href="https://mvnrepository.com/artifact/gg.jte/jte-spring-boot-starter-3">jte-spring-boot-starter-3</a><a href="https://mvnrepository.com/artifact/gg.jte/jte">jte</a> 依賴項添加到我們的 <em>pom.xml</em> 中:

<dependency>
    <groupId>gg.jte</groupId>
    <artifactId>jte-spring-boot-starter-3</artifactId>
    <version>3.1.15</version>
</dependency>
<dependency>
    <groupId>gg.jte</groupId>
    <artifactId>jte</artifactId>
    <version>3.1.15</version>
</dependency> 

在我們的 Spring Boot 版本為 2 的情況下,需要使用 jte-spring-boot-starter-2 代替:

<dependency>
    <groupId>gg.jte</groupId>
    <artifactId>jte-spring-boot-starter-2</artifactId>
    <version>3.1.15</version>
</dependency>

默認情況下,啓動配置會設置模板引擎和視圖解析器。此外,它期望我們的模板文件位於 src/java/main/jte 目錄下,位於主目錄中。

但是,我們可以在 application.properties 文件中進行覆蓋:

gg.jte.templateLocation=src/main/resources/jte

在此,我們明確指定了模板文件的自定義位置。

此外,還需要在 application.properties 文件中設置模板後綴和開發模式:

gg.jte.templateSuffix=.jte
gg.jte.developmentMode=true

當開發模式設置為 true 時,模板文件中所做的任何更改都將自動更新。

9. 其他模板引擎

除了前面所描述的模板引擎之外,還有許多其他可用的模板引擎可以被使用。

我們簡要回顧一下它們。

Velocity 是一款較老的模板引擎,雖然功能非常強大,但缺點是由於 Spring 從版本 4.3 開始棄用它,並在 Spring 5.0.1 中完全移除。

JMustache 是一個易於集成到 Spring Boot 應用程序中的模板引擎,可以通過 spring-boot-starter-mustache 依賴項來實現。

Pebble 包含對 Spring 和 Spring Boot 的支持,其庫中就包含了這些支持。

諸如 HandlebarsReact 這樣的模板庫,以及在 JSR-223 腳本引擎(如 Nashorn 上運行,也可以被使用。

結論

本文介紹了 Spring Web 應用程序中最流行的模板引擎。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.