Thymeleaf對象的使用:基本對象


Thymeleaf中有許多內置對象,可以在模板中實現各種功能。
下面有幾個基本對象。
Web對象常用有:request、session、servletContext。
Thymeleaf提供了幾個內置變量param、session、application,分別可以訪問請求參數、session屬性、application屬性。
其中request的所有屬性可以直接使用 ${屬性名} 訪問。
備注:內置對象與內置變量是兩個概念,內置對象使用“${#對象}”形式,內置變量則不需要“#”。

開發環境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一個名稱為demo的Spring Boot項目。

1、pom.xml加入Thymeleaf依賴:

        <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

 


免責聲明!

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



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