当前位置: 移动技术网 > IT编程>开发语言>Java > Thymeleaf对象的使用之基本对象实例解析

Thymeleaf对象的使用之基本对象实例解析

2020年05月13日  | 移动技术网IT编程  | 我要评论

bitchina,三生三世菩提劫,湖北三本大学

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网