1. 使用maven构建SpringBoot的名叫spring-boot-view-thymeleaf-scope项目
2. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bjbs</groupId>
<artifactId>spring-boot-view-thymeleaf-scope</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
</parent>
<!-- 修改jdk版本 -->
<properties>
<java.version>1.8</java.version>
<!-- 指定thymeleaf和thymeleaf-layout-dialect高版本可以防止html标签不规范报错 -->
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
3. 在src/main/resources/templates下新建scope.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Thymeleaf获取作用域对象中的数据</title>
</head>
<body>
Request: <span th:text="${#httpServletRequest.getAttribute('req')}"></span><br/>
Session: <span th:text="${session.sess}"></span><br/>
Application: <span th:text="${application.app}"></span>
</body>
</html>
4. 新建UserController.java
package com.bjbs.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
@RequestMapping("/scope")
public String scope(HttpServletRequest request, Model model) {
request.setAttribute("req", "Request作用域中的参数");
request.getSession().setAttribute("sess", "Session作用域中的参数");
request.getSession().getServletContext().setAttribute("app", "Application作用域中的参数");
return "scope";
}
}
5. 新建App.java
package com.bjbs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SpringBoot启动类
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
6. 启动项目, 并使用浏览器访问