There are many built-in objects in Thymeleaf, which can implement various functions in templates.
There are a few basic objects below.
Commonly used web objects are: request, session, and servletContext.
Thymeleaf provides several built-in variables param, session, and application, which can respectively access request parameters, session attributes, and application attributes.
All the attributes of request can be directly accessed using ${attribute name}.
Note: Built-in objects and built-in variables are two concepts. Built-in objects use the form "${#object}", and built-in variables don't need "#".
Development environment: IntelliJ IDEA 2019.2.2
Spring Boot version: 2.1.8
Create a new Spring Boot project named demo.
1. Add the Thymeleaf dependency to 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";
}
}
Browser access: http://localhost:8080/test1?name1=a
Page output:
a
b
c
d
上面也可以换成下面方式:
b
c
d