ホームページ  >  記事  >  Java  >  SpringBoot の Thymeleaf テンプレートの詳細な紹介

SpringBoot の Thymeleaf テンプレートの詳細な紹介

不言
不言転載
2018-10-11 15:19:323263ブラウズ

この記事では、SpringBoot の Thymeleaf テンプレートについて詳しく説明します。必要な方は参考にしていただければ幸いです。

1. はじめに

JSP は古くから存在しており、Java で使用されてきましたが、Thymeleaf は JSP に代わるものとして登場しました。 Web 開発のどこにでもありますが、いくつかの欠陥もあります:

1. JSP の最も明白な問題は、JSP が HTML または XML のように見えますが、実際はそうではないことです。ほとんどの JSP テンプレートは HTML 形式ですが、さまざまな JSP タグ ライブラリのタグが混在しているため、非常に混乱します。

2. JSP 仕様はサーブレット仕様と密接に関係しています。これは、サーブレットベースの Web アプリケーションでのみ使用できることを意味します。 JSP テンプレートは、一般的なテンプレート (電子メールのフォーマットなど) として使用することはできません。また、サーブレット以外の Web アプリケーションで使用することもできません。

JSP と比較して、Thymeleaf はこれらの欠点をうまく解決します:

1. Thymeleaf テンプレートはネイティブであり、タグ ライブラリに依存しません。生の HTML が受け入れられる場合は、編集およびレンダリングできます。

2. サーブレット仕様と連動していないため、 タイムリーフ テンプレートは、JSP ができない領域に入ることができます。つまり、Thymeleaf テンプレートは、JSP とは異なり、いかなる処理も行わずに編集でき、元の形式でレンダリングすることもできます。もちろん、テンプレートを処理し、最終的に必要な出力をレンダリングするには、Thymeleaf が必要です。それでも、特別な処理を行わなくても、home.html を Web ブラウザに読み込むことができ、完全なレンダリングと同様に表示されます。

Spring Boot では、Web 開発に JSP を使用することはお勧めしません。

2. Thymeleaf テンプレート エンジンの統合

SpringBoot の Thymeleaf テンプレート エンジンのサポートも非常にシンプルです:

1、pom.xml

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

現時点で、SpringBoot の Thymeleaf テンプレートのサポートは完了し、Web 開発で Thymeleaf テンプレートを使用できるようになります。

以前の記事で言及した SpringBoot の鍵となるのは「規約」です。このような単純な構成を選択したため、開発中に Thymeleaf に対する SpringBoot の要件に準拠する必要があります。 従来のソリューションの最も重要な点は、テンプレート ファイルがテンプレート ディレクトリに配置されることです。つまり、テンプレート パーサーのプレフィックスが /templates/ で、サフィックスが .html

です。 2、application.yml

いわゆる従来のソリューションを必要とせず、カスタマイズされた構成を作成したい場合はどうすればよいでしょうか?以下を参照してください:

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    servlet:
      content-type: text/html
    enabled: true
    encoding: UTF-8
    mode: HTML5
    cache: false

3, WebConfig.java

上記の構成では要件を満たせない場合は、ビュー パーサー、テンプレート パーサー、テンプレートの構成など、Thymeleaf をより詳細に制御する必要があります。エンジンの場合は、以下の解決策を参照してください。

/**
 * 1、ThymeleafViewResolver 接收逻辑视图名称将它解析为视图
 * 2、SpringTemplateEngine会在Spring中启用Thymeleaf引擎,用来解析模板,并基于这些模板渲染结果
 * 3、TemplateResolver会最终定位和查找模板。
 */
@Configuration
public class WebConfig {
    /**
     * 配置 Thymeleaf 视图解析器 —— 将逻辑视图名称解析为 Thymeleaf 模板视图
     *
     * @param springTemplateEngine 模板引擎
     * @return
     */
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine springTemplateEngine){
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(springTemplateEngine);
        return resolver;
    }
    /**
     * 模板引擎 —— 处理模板并渲染结果
     *
     * @param templateResolver 模板解析器
     * @return
     */
    @Bean
    public SpringTemplateEngine springTemplateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.setTemplateResolver(templateResolver);
        return springTemplateEngine;
    }
    /**
     * 模板解析器 —— 加载 Thymeleaf 模板
     *
     * @return
     */
    @Bean
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }
}

3. Thymeleaf テンプレートを使用する

上記の設定を完了したら、SpringBoot で Thymeleaf テンプレートを使用する方法を見てみましょう:

#1. テンプレート ファイル - /templates/user/list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h2>用户列表</h2>
<div>
    <ul>
        <li  th:each="user:${users}">
            <span th:text="${user.uuid}"></span>-
            <span th:text="${user.name}"></span>-
            <span th:text="${user.age}"></span>-
            <span th:text="${user.address}"></span>
        </li>
    </ul>
</div>
</body>
</html>

2. コントロール層 - ModelAndViews

ここでのモデルは「はい」を指します。コントロール層はリクエストを処理し、レンダリングする必要がある結果を返します。ビューは、テンプレートの論理ビュー名(フロントエンドとバックエンドから分離)を参照します。

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/list")
    public String listUser(Model model) {
        List<UserDto> userList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            userList.add(new UserDto(UUID.randomUUID().toString().replace("-", ""), "张三" + i, 1, "中国北京"));
        }
        model.addAttribute("users", userList);
        return "user/list";
    }
}

3. 効果

SpringBoot の Thymeleaf テンプレートの詳細な紹介##デモ ソース コード:

https:/ / github.com/JMCuixy/Thymeleaf

以上がSpringBoot の Thymeleaf テンプレートの詳細な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はcnblogs.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。