温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Thymeleaf的基本对象怎么使用

发布时间:2022-01-20 17:49:17 来源:亿速云 阅读:123 作者:iii 栏目:web开发

这篇文章主要介绍“Thymeleaf的基本对象怎么使用”,在日常操作中,相信很多人在Thymeleaf的基本对象怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”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

到此,关于“Thymeleaf的基本对象怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI