内置对象
官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
内置对象可以在模板中直接使用
#request表示HttpServletRequest对象
#session表示HttpSession对象
session表HttpSession对象,是#session的简单表达方式
举例,创建一个新的Springboot项目,添加Thymeleaf和web依赖
在static下创建index页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>内置对象,工具类</title>
</head>
<body>
<a href="UrlRequest">内置对象</a>
</body>
</html>
在java目录下创建controller类
package com.ys.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class ZController {
@GetMapping("/UrlRequest")
public String UrlRequest(HttpServletRequest request, HttpSession session){
request.setAttribute("requestData","request作用域");
request.getSession().setAttribute("sessionData","session作用域");
//直接使用session
session.setAttribute("s","直接使用session");
return "UrlRequest";
}
}
在templates下创建页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>#request</title>
</head>
<body>
<h3>#request表示HttpServletRequest对象</h3>
<p>获取作用域中的数据</p>
<p th:text="${#request.getAttribute('requestData')}"></p>
<p th:text="${#session.getAttribute('sessionData')}"></p>
<p th:text="${session.s}"></p>
<p th:text="${requestData}"></p>
<!-- <p th:text="${s}"></p>
<p th:text="${sessionData}"></p>
使用session时,不能直接使用定义的变量名进行值的输出
但是request可以-->
<h3>request内置方法演示</h3>
<!--完整地址-->
getRequestURL=<span th:text="${#request.getRequestURL()}"></span><br>
<!--除去端口和本地ip的剩下的地址-->
getRequestURI=<span th:text="${#request.getRequestURI()}"></span><br>
<!--获取查询字符串,只对get方法有效-->
getQueryString=<span th:text="${#request.getQueryString()}"></span><br>
<!--获取上下文,可以在application中配置-->
getContextPath=<span th:text="${#request.getContextPath()}"></span><br>
<!--获取ip-->
getServerName=