Thymeleafオブジェクトの使用:基本オブジェクト

Thymeleafには多くの組み込みオブジェクトがあり、テンプレートにさまざまな機能を実装できます。
以下にいくつかの基本的なオブジェクトがあります。
一般的に使用されるWebオブジェクトは、request、session、servletContextです。
Thymeleafには、いくつかの組み込み変数param、session、およびapplicationが用意されており、それぞれ要求パラメーター、セッション属性、およびアプリケーション属性にアクセスできます。
リクエストのすべての属性には、$ {属性名}を使用して直接アクセスできます。
備考:組み込みオブジェクトと組み込み変数は2つの概念です。組み込みオブジェクトは「$ {#object}」の形式を使用し、組み込み変数は「#」を必要としません。

開発環境:IntelliJ IDEA 2019.2.2
Spring Bootバージョン:2.1.8

demoという名前の新しいSpringBootプロジェクトを作成します。

1.Thymeleaf依存関係をpom.xmlに追加します。

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

2、src / main / resources / templates / test1.html

<div th:text="${param.name1}"></div>

<div th:text="${#request.getAttribute('name2')}"></div>
<div th:text="${#session.getAttribute('name3')}"></div>
<div th:text="${#servletContext.getAttribute('name4')}"></div>
上面也可以换成下面方式:
<div th:text="${name2}"></div>
<div th:text="${session.name3}"></div>
<div th:text="${application.name4}"></div>

3、src / main / java / com / example / demo / Test1Controller.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class Test1Controller {
    @RequestMapping("/test1")
    public String test1(@RequestParam String name1, HttpServletRequest request){
        request.setAttribute("name2", "b");
        request.getSession().setAttribute("name3", "c");
        request.getServletContext().setAttribute("name4","d");
        return "test1";
    }
}

ブラウザアクセス:http:// localhost:8080 / test1?name1 = a
ページ出力:

a
b
c
d
上面也可以换成下面方式:
b
c
d

 

おすすめ

転載: blog.csdn.net/gdjlc/article/details/102512105
おすすめ