SpringBoot整合模板引擎Thymeleaf(2)


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

概述

Thymeleaf十分类似于JSP中使用的EL表达式。整体而言,Thymeleaf简洁、优雅、高效;非常适合小型项目的快速开发。

Thymeleaf常用标签简述

在此,概要介绍Thymeleaf常用标签。

标签功能示例
th:text显示文本<p th:text="${collect.description}">description</p>
th:utext显示文本(对特殊标签不转义)<p th:utext="${htmlcontent}">conten</p>
th:value为表单元素的value属性赋值<input th:value="${user.name}" />
th:if判断条件<a th:if="${userId == collect.userId}" >
th:each元素遍历tr th:each="user,userStat:${users}">
th:id标记控件<input th:id="'xxx' + ${collect.id}"/>
th:object替换对象<div th:object="${session.user}">
th:with变量赋值(定义局部变量)<div th:with="isEven=${prodStat.count}%2==0"></div>
th:style设置样式th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick点击事件th:onclick="'getCollect()'"
th:unless和th:if判断相反<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href链接地址<a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch多路选择,配合th:case 使用<div th:switch="${user.role}">
th:caseth:switch的一个分支<p th:case="'admin'">User is an administrator</p>
th:fragment片段声明<div th:fragment="alert">
th:include片段包含<head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:insert片段插入<div th:insert="fragments/header :: title"></div>
th:replace片段替换<div th:replace="fragments/header :: title"></div>
th:selected选中th:selected="(${xxx.id} == ${configObj.dd})"
th:src外部资源地址<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline定义js脚本可以使用变量<script type="text/javascript" th:inline="javascript">
th:action表单提交地址<form action="subscribe.html" th:action="@{/subscribe}">
th:remove删除某个属性<tr th:remove="all">
th:attr设置标签属性,多个属性可以用逗号分隔th:attr="src=@{/image/aa.jpg},title=#{logo}"

Thymeleaf表达式

在此,详细介绍Thymeleaf常用表达式。

语法说明作用
${…}变量表达式取出上下文变量的值
*{…}选择变量表达式取出选择的对象的属性值
#{…}消息表达式使文字消息国际化
@{…}链接表达式用于表示超链接地址
~{…}片段表达式引用公共的代码片段

变量表达式

变量表达式用于从上下文获取变量值。

示例如下:

<p th:text="${message}">默认值</p>

选择变量表达式

选择变量表达式用于从被选择的对象获取属性值。

示例如下:

<div th:object="${session.user}">
    <p th:text="*{name}"></p>
    <p th:text="*{gender}"></p>
    <p th:text="*{age}"></p>
</div>

等同于:

<div>
    <p th:text="${session.user.name}"></p>
    <p th:text="${session.user.gender}"></p>
    <p th:text="${session.user.age}"></p>
</div>

消息表达式

消息表达式主要用于国际化。稍后,再详细介绍。

链接表达式

链接表达式用于处理 URL 链接地址。链接地址可以是相对地址,也可以是绝对地址亦可以在地址中携带参数。

在实际开发过程中,我们通常使用链接表达式实现链接、引入CSS、引入JS。

示例如下:

<p th:text="@{https://www.heidu.com}"></p>
<p th:text="@{commons/base.html}"></p>
<!-- /css/mian.css?v=1.0 -->
<p th:text="@{/css/mian.css(v=1.0)}"></p>
<!-- /user/order?username=lucy -->
<p th:text="@{/user/order(username=${session.user.name})}"></p>
<!-- /user/order?username=lucy&status=ok -->
<p th:text="@{/user/order(username=${session.user.name},status='ok')}"></p>
<!-- /user/lucy/info -->
<p th:text="@{/user/{username}/info(username=${session.user.name})}"></p>

片段表达式

片段表达式用于引用一段公共的 HTML 代码片段。常用th:insert和th:replace引用公共的代码片段;两者的区别在于:th:insert是直接将代码片段插入到标签体内,而th:replace则是用代码片段直接替换标签体内容。

<!-- /views/common/head.html-->
<head th:fragment="jsFragment">
        <script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
</head>

<!-- /views/your.html -->
<div th:replace="~{common/head::jsFragment}"></div>

Thymeleaf行内写法

在这里插入图片描述

Thymeleaf常见的行内写法有两种:

  • [[…]] 等效于 th:text

  • [(…)] 等效于th:utext

在实际开发过程中,我们通常使用"[[@{/}]]"在前端页面获取项目名

示例如下:

let contextPath = "[[@{/}]]";

Thymeleaf核心技术示例

在此,以示例形式详细介绍Thymeleaf核心技术。

项目结构

要点概述:

  • 1、static文件夹用于存放静态资源,例如:css文件、js文件、图片。
  • 2、templates用于存放使用了Thymeleaf的html文件。
  • 3、entity包用于存放实体,例如:User、Student等。
    在这里插入图片描述

依赖文件

请在pom.xml文件中添加如下依赖。

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cn</groupId>
    <artifactId>SpringBootThymeleaf01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootThymeleaf01</name>
    <description>SpringBootThymeleaf01</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件

请在application.properties文件添加以下配置。

# 缓存设置。开发中设置为false,线上时设置为true
spring.thymeleaf.cache=false
# 模板的编码方式
spring.thymeleaf.encoding=UTF-8
# 模式
spring.thymeleaf.mode=HTML5
# 模板页面存放路径
spring.thymeleat.prefix=classpath:/resources/templates/
# 模板页面名称后缀
spring.thymeleaf.suffix=.html

Student

package com.cn.springbootthymeleaf01.entity;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class Student {
    private String name;
    private int age;
    private String gender;

    public Student() {
    }

    public Student(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

User

在User中其birthday字段类型为java.util.Date。

package com.cn.springbootthymeleaf01.entity;

import java.util.Date;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class User {
    private Integer id;
    private String name;
    private Double salary;
    private Date birthday;

    public User() {
    }

    public User(Integer id, String name, Double salary, Date birthday) {
        this.id = id;
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }
}

SpringBootThymeleaf01Application

package com.cn.springbootthymeleaf01;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
@SpringBootApplication
public class SpringBootThymeleaf01Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootThymeleaf01Application.class, args);
    }

}

在这里插入图片描述

Thymeleaf常用标签及数据传递

在此,详细介绍Thymeleaf常用标签

TestController1

package com.cn.springbootthymeleaf01.controller;

import com.cn.springbootthymeleaf01.entity.Student;
import com.cn.springbootthymeleaf01.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
@Controller
@RequestMapping("/MyController1")
public class TestController1 {
    @RequestMapping("/test1")
    public String test1(HttpServletRequest httpServletRequest){
        // 传递基本类型数据
        String name = "谷哥的小弟";
        httpServletRequest.setAttribute("name",name);

        // 传递基本类型数据并进行条件判断
        int age = 19;
        httpServletRequest.setAttribute("age",age);

        // 传递带标签的数据
        String htmlContent = "<a href='https://blog.csdn.net/lfdfhl'>本文作者:谷哥的小弟</a>";
        httpServletRequest.setAttribute("htmlContent",htmlContent);

        // 为标签的value属性传递值
        String city = "北京";
        httpServletRequest.setAttribute("city",city);

        // 传递对象
        Student student = new Student("zxx",19,"man");
        httpServletRequest.setAttribute("student",student);

        // 传递对象
        User user = new User(9527, "zxc", 4500.5, new Date());
        httpServletRequest.setAttribute("user", user);

        // 传递集合
        Student student1 = new Student("wmd",19,"man");
        Student student2 = new Student("puy",20,"man");
        Student student3 = new Student("tep",21,"man");
        Student student4 = new Student("cvb",22,"man");
        List<Student> studentList = new ArrayList<Student>();
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        httpServletRequest.setAttribute("studentList",studentList);

        // 跳转至index.html
        return "index1";
    }
}

index1.html

<!DOCTYPE html>
<!--  引入Thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Hello Thymeleaf</title>
</head>
<body>
<h2 style="color: red;">本文作者:谷哥的小弟</h2>
<h2 style="color: red;">博客地址:http://blog.csdn.net/lfdfhl</h2>
<br/>
获取基本类型数据:
<span th:text="${name}"></span>
<hr/>
获取基本类型数据并进行条件判断:
<div style="width: 300px;height: 50px;background: green;" th:if="${age>=18}">
  age大于等于18,可以去网吧。
</div>
<div style="width: 300px;height: 50px;background: red;" th:if="${age<18}">
  age小于18,不可以去网吧。
</div>
<hr/>
获取带标签的数据:
<span th:utext="${htmlContent}"></span>
<hr/>
获取为标签value属性传递的值
<input type="text" name="username" th:value="${city}">
<hr/>
获取对象:
name:<span th:text="${student.name}"></span>
age:<span th:text="${student.age}"></span>
gender:<span th:text="${student.gender}"></span>
<hr/>
获取对象:
id:<span th:text="${user.id}"></span>
name:<span th:text="${user.name}"></span>
salary:<span th:text="${user.salary}"></span>
birthday:<span th:text="${#dates.format(user.birthday,'yyy-MM-dd HH:mm:ss')}"></span>
<hr/>
获取集合:
<ul>
  <li th:each="student,state:${studentList}">
    state count: <span th:text="${state.count}"></span>
    state odd : <span th:text="${state.odd}"></span>
    state even : <span th:text="${state.even}"></span>
    state size : <span th:text="${state.size}"></span>
    name:<span th:text="${student.name}"></span>
    age:<span th:text="${student.age}"></span>
    gender:<span th:text="${student.gender}"></span>
  </li>
</ul>
</body>
</html>

在这里插入图片描述

测试地址

http://localhost:8080/MyController1/test1

th:text

该标签用于显示普通文本。

Controller中代码如下:

// 传递基本类型数据
String name = "谷哥的小弟";
httpServletRequest.setAttribute("name",name);

html中代码如下:

获取基本类型数据:
<span th:text="${name}"></span>
<hr/>

th:if

该标签用于条件判断。当判断的结果为true时显示元素;反之,不显示。

Controller中代码如下:

// 传递基本类型数据并进行条件判断
int age = 19;
httpServletRequest.setAttribute("age",age);

html中代码如下:

获取基本类型数据并进行条件判断:
<div style="width: 300px;height: 50px;background: green;" th:if="${age>=18}">
  age大于等于18,可以去网吧。
</div>
<div style="width: 300px;height: 50px;background: red;" th:if="${age<18}">
  age小于18,不可以去网吧。
</div>
<hr/>

th:utext

该标签用于显示带有网页标签的文本。

Controller中代码如下:

// 传递带标签的数据
String htmlContent = "<a href='https://blog.csdn.net/lfdfhl'>本文作者:谷哥的小弟</a>";
httpServletRequest.setAttribute("htmlContent",htmlContent);

html中代码如下:

获取带标签的数据:
<span th:utext="${htmlContent}"></span>
<hr/>

th:value

该标签用于为标签value属性传递值。

Controller中代码如下:

// 为标签的value属性传递值
String city = "北京";
httpServletRequest.setAttribute("city",city);

html中代码如下:

获取为标签value属性传递的值
<input type="text" name="username" th:value="${city}">
<hr/>

传递对象

将对象保存至Request域并在html文件中获取。

传递Student

Controller中代码如下:

// 传递对象
Student student = new Student("zxx",19,"man");
httpServletRequest.setAttribute("student",student);

html中代码如下:

获取对象:
name:<span th:text="${student.name}"></span>
age:<span th:text="${student.age}"></span>
gender:<span th:text="${student.gender}"></span>
<hr/>

在html页面中通过对象名.属性的方式获取相应的值。

传递User

Controller中代码如下:

// 传递对象
User user = new User(9527, "zxc", 4500.5, new Date());
httpServletRequest.setAttribute("user", user);

html中代码如下:

获取对象:
id:<span th:text="${user.id}"></span>
name:<span th:text="${user.name}"></span>
salary:<span th:text="${user.salary}"></span>
birthday:<span th:text="${#dates.format(user.birthday,'yyy-MM-dd HH:mm:ss')}"></span>
<hr/>

利用Spring Boot自带工具类#dates格式化日期。

传递集合

Controller中代码如下:

// 传递集合
Student student1 = new Student("wmd",19,"man");
Student student2 = new Student("puy",20,"man");
Student student3 = new Student("tep",21,"man");
Student student4 = new Student("cvb",22,"man");
List<Student> studentList = new ArrayList<Student>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
httpServletRequest.setAttribute("studentList",studentList);

html中代码如下:

获取集合:
<ul>
  <li th:each="student,state:${studentList}">
    state count: <span th:text="${state.count}"></span>
    state odd : <span th:text="${state.odd}"></span>
    state even : <span th:text="${state.even}"></span>
    state size : <span th:text="${state.size}"></span>
    name:<span th:text="${student.name}"></span>
    age:<span th:text="${student.age}"></span>
    gender:<span th:text="${student.gender}"></span>
  </li>
</ul>

在html中利用th:each遍历集合,语法如下:

th:each="元素,state:${集合}"
  • 1、集合表示待遍历集合
  • 2、元素表示遍历过程中得到的当前元素
  • 3、state表示当前元素和集合的状态

保存数据至Session域和Application域

在之前的示例中,均是把数据保存到Request域。除此以外,我们还可以将
数据至Session域和Application域。

TestController2

package com.cn.springbootthymeleaf01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
@Controller
@RequestMapping("/MyController2")
public class TestController2 {
    @RequestMapping("/test2")
    public String test2(HttpServletRequest httpServletRequest){
        // 将数据保存至session域
        String name = "谷哥的小弟";
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("name",name);

        // 将数据保存至application域
        ServletContext servletContext = httpServletRequest.getServletContext();
        int age = 27;
        servletContext.setAttribute("age",age);

        // 跳转至index2.html
        return "index2";
    }
}

index2.html

<!DOCTYPE html>
<!--  引入Thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Hello Thymeleaf</title>
</head>
<body>
<h2 style="color: red;">本文作者:谷哥的小弟</h2>
<h2 style="color: red;">博客地址:http://blog.csdn.net/lfdfhl</h2>
<br/>
从session域获取数据:
name:<span th:text="${session.name}"></span>
<hr/>

从application域获取数据:
age:<span th:text="${application.age}"></span>
<hr/>

</body>
</html>

在这里插入图片描述

测试地址

http://localhost:8080/MyController2/test2

保存数据至Session域

Controller中代码如下:

// 将数据保存至session域
String name = "谷哥的小弟";
HttpSession session = httpServletRequest.getSession();
session.setAttribute("name",name);

html中代码如下:

从session域获取数据:
name:<span th:text="${session.name}"></span>
<hr/>

在前端页面中通过session.的方式获取数据。

保存数据至Application域

Controller中代码如下:

// 将数据保存至application域
ServletContext servletContext = httpServletRequest.getServletContext();
int age = 27;
servletContext.setAttribute("age",age);

html中代码如下:

从application域获取数据:
age:<span th:text="${application.age}"></span>
<hr/>

在前端页面中通过application.的方式获取数据。

利用Model保存数据

在之前的示例中,均是把数据保存到Request域、Session域、Application域。除此以外,还可以利用Model保存数据

TestController3

package com.cn.springbootthymeleaf01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
@Controller
@RequestMapping("/MyController3")
public class TestController3 {
    @RequestMapping("/test3")
    public String test3(HttpServletRequest httpServletRequest, Model model){
        // 利用Model保存数据
        String name = "谷哥的小弟";
        model.addAttribute("name",name);
        int age = 27;
        model.addAttribute("age",age);

        // 跳转至index3.html
        return "index3";
    }
}


index3.html

<!DOCTYPE html>
<!--  引入Thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Hello Thymeleaf</title>
</head>
<body>
<h2 style="color: red;">本文作者:谷哥的小弟</h2>
<h2 style="color: red;">博客地址:http://blog.csdn.net/lfdfhl</h2>
<br/>
从Model获取数据:
name:<span th:text="${name}"></span>
age:<span th:text="${age}"></span>
<hr/>

</body>
</html>

在这里插入图片描述

测试地址

http://localhost:8080/MyController3/test3

重定向

在Spring Boot + Thymeleaf 的开发环境中通常利用 return "redirect:Controller"的方式进行重定向。也就是说:利用redirect重定向至其它Controller。

需要注意的是:在进行重定向时不可利用Request和Model保存数据;而应该使用Session和Application域保存数据。否则,重定向之后的页面无法获取数据进行显示。

TestController4

package com.cn.springbootthymeleaf01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
@Controller
@RequestMapping("/MyController4")
public class TestController4 {
    @RequestMapping("/test4")
    public String test4(HttpServletRequest httpServletRequest, Model model){

        // 利用HttpServletRequest保存数据(wrong)
        String city = "北京";
        httpServletRequest.setAttribute("city", city);

        // 利用Model保存数据(wrong)
        String name = "谷哥的小弟";
        model.addAttribute("name",name);
        int age = 27;
        model.addAttribute("age",age);

        // 将数据保存至session域
        String author = "lfdfhl";
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("author",author);

        // 将数据保存至application域
        ServletContext servletContext = httpServletRequest.getServletContext();
        int number = 9527;
        servletContext.setAttribute("number",number);

        // 重定向至/MyController4/testRedirect
        return "redirect:/MyController4/testRedirect";
    }

    @RequestMapping("/testRedirect")
    public String testRedirect(){
        return "index4";
    }
}

index4.html

<!DOCTYPE html>
<!--  引入Thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Hello Thymeleaf</title>
</head>
<body>
<h2 style="color: red;">本文作者:谷哥的小弟</h2>
<h2 style="color: red;">博客地址:http://blog.csdn.net/lfdfhl</h2>
<br/>
从Request获取数据(wrong):
city:<span th:text="${city}"></span>
<hr/>
从Model获取数据(wrong):
name:<span th:text="${name}"></span>
age:<span th:text="${age}"></span>
<hr/>
从session域获取数据:
author:<span th:text="${session.author}"></span>
<hr/>
从application域获取数据:
number:<span th:text="${application.number}"></span>
<hr/>
</body>
</html>

在这里插入图片描述

测试地址

http://localhost:8080/MyController4/testRedirect

请求转发

在Spring Boot + Thymeleaf 的开发环境中通常利用 return "forward:Controller"的方式进行请求转发。也就是说:利用forward请求转发至其它Controller。

TestController5

package com.cn.springbootthymeleaf01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
@Controller
@RequestMapping("/MyController5")
public class TestController5 {
    @RequestMapping("/test5")
    public String test4(HttpServletRequest httpServletRequest, Model model){

        // 利用HttpServletRequest保存数据
        String city = "北京";
        httpServletRequest.setAttribute("city", city);

        // 利用Model保存数据
        String name = "谷哥的小弟";
        model.addAttribute("name",name);
        int age = 27;
        model.addAttribute("age",age);

        // 将数据保存至session域
        String author = "lfdfhl";
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("author",author);

        // 将数据保存至application域
        ServletContext servletContext = httpServletRequest.getServletContext();
        int number = 9527;
        servletContext.setAttribute("number",number);

        // 请求转发至/MyController5/testForward
        return "forward:/MyController5/testForward";
    }

    @RequestMapping("/testForward")
    public String testForward(){
        return "index5";
    }
}

index5.html

<!DOCTYPE html>
<!--  引入Thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Hello Thymeleaf</title>
</head>
<body>
<h2 style="color: red;">本文作者:谷哥的小弟</h2>
<h2 style="color: red;">博客地址:http://blog.csdn.net/lfdfhl</h2>
<br/>
从Request获取数据:
city:<span th:text="${city}"></span>
<hr/>
从Model获取数据:
name:<span th:text="${name}"></span>
age:<span th:text="${age}"></span>
<hr/>
从session域获取数据:
author:<span th:text="${session.author}"></span>
<hr/>
从application域获取数据:
number:<span th:text="${application.number}"></span>
<hr/>
</body>
</html>

在这里插入图片描述

测试地址

http://localhost:8080/MyController5/test5

引入静态资源

在开发中,常需要引入已经定义好的静态资源,例如:css、js、图片。

引入css,语法如下:

<!--  通过th:href引入static中的css文件 -->
<link th:href="@{/css文件名}" rel="stylesheet">

引入js,语法如下:

<!--  通过th:src引入static中的js文件 -->
<script th:src="@{/js文件名}"></script>

引入图片,语法如下:

<!--  通过th:src引用static中的图片 -->
<img th:src="@{/文件名}" />

TestController6

package com.cn.springbootthymeleaf01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
@Controller
@RequestMapping("/MyController6")
public class TestController6 {
    @RequestMapping("/test6")
    public String test6(HttpServletRequest httpServletRequest, Model model){
        // 利用Model保存数据
        String name = "谷哥的小弟";
        model.addAttribute("name",name);
        int age = 27;
        model.addAttribute("age",age);

        // 跳转至index6.html
        return "index6";
    }
}

index6.html

<!DOCTYPE html>
<!--  引入Thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Hello Thymeleaf</title>
  <!--  通过th:href引入static中的css文件 -->
  <link th:href="@{/test.css}" rel="stylesheet">
  <!--  通过th:src引入static中的js文件 -->
  <script th:src="@{/test.js}"></script>
  <!-- 使用js文件中的函数-->
  <script>
    showDialog();
  </script>
  <!-- 获取项目名并在控制台打印 -->
  <!-- 该项目没有配置项目项目名,所以打印结果为 /-->
  <script>
    let contextPath = "[[@{/}]]";
    console.log("项目名:"+contextPath)
  </script>
</head>
<body>
<h2 style="color: red;">本文作者:谷哥的小弟</h2>
<h2 style="color: red;">博客地址:http://blog.csdn.net/lfdfhl</h2>
<br/>
从Model获取数据:
name:<span th:text="${name}"></span>
age:<span th:text="${age}"></span>
<hr/>
<!--  通过th:src引用static中的图片 -->
<img th:src="@{/icon.jpg}" width="72" height="72"/>
</body>
</html>

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

测试路径

http://localhost:8080/MyController6/test6

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/32115.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Socket安全(一)

文章目录 1. 安全Socket2. 保护通信3. 创建安全客户端Socket4. 选择密码组5. 事件处理器6. 会话管理 1. 安全Socket 前面介绍了Socket的基本使用&#xff0c;这里开始介绍Socket的安全问题&#xff0c;作为一个Internet用户&#xff0c;你确实有一些保护手段可以保护自己的隐私…

【MongoDB】四、MongoDB副本集的部署

【MongoDB】四、MongoDB副本集的部署 实验目的实验内容实验步骤实验小结 实验目的 能够通过部署副本集理解副本集机制&#xff0c;从而解决大数据项目中数据丢失的问题 实验内容 环境准备&#xff1a;根据表中的信息完成3台MongoDB服务器的部署&#xff08;XXX是姓名拼音首字母…

Linux下使用Samba做域控

AI画妹子的工作先暂告一段落。毕竟戗行也是要有门槛的。 企业中使用Windows Server使用活动目录集中管理PC、服务器是很成熟的方案。突然想到&#xff0c;如果有一天出于某种原因不再使用微软方案了&#xff0c;AD该如何替代&#xff1f;问了一下chatGPT&#xff0c;它说&…

简易MFC的成绩管理系统

意义 掌握MFC控件的基本使用&#xff0c;结合了面向对象和Window消息机制的知识。 选择做简单的成绩管理系统&#xff0c;该项目切合大学生实际情况。易于更好理解。 项目实现了成绩的增加、修改、删除、存储&#xff08;文件读写操作&#xff09;的功能。 创建项目 打开软件…

浅谈企业能源监测管理系统的设计与应用

安科瑞 华楠 摘要: 针对企业目前能源监测现状, 结合企业信息化建设情况和发展需要, 介绍了能源监测管理信息系统, 提出了企业能源监测管理系统建设建议。 关键词:管理系统; 能源监测; 企业信息化 0 引言 节能降耗是缓解中国资源约束的根本出路, 也是提高企业自主创新能力的…

Vault从入门到精通系列之二:启动Vault服务器

Vault从入门到精通系列之二&#xff1a;启动Vault服务器 一、启动开发服务器二、设置环境变量三、验证服务器正在运行四、vault命令汇总 Vault 作为客户端-服务器应用程序运行。Vault 服务器是唯一与数据存储和后端交互的 Vault 架构。通过 Vault CLI 完成的所有操作都通过 TLS…

【并发知识点】CAS的实现原理及应用

系列文章目录 AQS的实现原理及应用 CAS的实现原理及应用 文章目录 系列文章目录前言1、CAS的概念2、CAS的实现原理3、单JVM内锁CAS实现3.1、效果 4、模拟赛龙舟比赛 前言 本章节介绍CAS概念、实现原理&#xff0c;并通过java代码应用&#xff0c;最终模拟赛龙舟比赛。 1、CA…

【spring cloud学习】2、Eureka服务注册与发现

前言 一套微服务架构的系统由很多单一职责的服务单元组成&#xff0c;而每个服务单元又有众多运行实例。由于各服务单元颗粒度较小、数量众多&#xff0c;相互之间呈现网状依赖关系&#xff0c;因此需要服务注册中心来统一管理微服务实例&#xff0c;维护各服务实例的健康状态…

【HTML】常用标签

文章目录 1.标题字标签h1-h62.段落标签p3.换行标签br4.格式化标签5.图片标签6.超链接标签a7.表格标签单元格合并行合并列合并 8.无序列表9.有序列表10.自定义列表11.表单标签11.1 form标签11.2 表单控件11.2.1 input标签11.2.2 label标签11.2.3 select标签11.2.4 textarea标签 …

外网SSH远程连接linux服务器「cpolar内网穿透」

文章目录 视频教程1. Linux CentOS安装cpolar2. 创建TCP隧道3. 随机地址公网远程连接4. 固定TCP地址5. 使用固定公网TCP地址SSH远程 转载自内网穿透工具的文章&#xff1a;无公网IP&#xff0c;SSH远程连接Linux CentOS服务器【内网穿透】 本次教程我们来实现如何在外公网环境下…

两阶段目标检测指南:R-CNN、FPN、Mask R-CNN

动动发财的小手&#xff0c;点个赞吧&#xff01; Source[1] 多阶段&#xff08;Two-stage&#xff09;物体检测 计算机视觉中最基本和最广泛研究的挑战之一是目标检测。该任务旨在在给定图像中绘制多个对象边界框&#xff0c;这在包括自动驾驶在内的许多领域非常重要。通常&am…

2022年长三角高校数学建模竞赛B题齿轮箱故障诊断解题全过程文档及程序

2022年长三角高校数学建模竞赛 B题 齿轮箱故障诊断 原题再现&#xff1a; 齿轮箱是用于增加输出扭矩或改变电机速度的机械装置&#xff0c;被广泛应用于如汽车、输送机、风机等机械设备中。它由两个或多个齿轮组成&#xff0c;其中一个齿轮由电机驱动。电机的轴连接到齿轮箱的…

SpringMvc入门

SpringMvc用来代替展示层Servlet&#xff0c;均属于Web层开发技术 Servlet是如何工作的 1、导入Servlet依赖坐标 2、创建一个Servlet接口实现类&#xff0c;重写其中的所有方法 3、在Servlet实现类上加上WebServlet注解&#xff0c;用来配置Servlet访问路径 4、启动Tomca…

总结906

学习目标&#xff1a; 月目标&#xff1a;6月&#xff08;线性代数强化9讲&#xff0c;背诵15篇短文&#xff0c;考研核心词过三遍&#xff09; 周目标&#xff1a;线性代数强化3讲&#xff0c;英语背3篇文章并回诵&#xff0c;检测 每日规划 今日已做&#xff1a; 1.回环背诵…

详解Hystrix

目录 1.微服务中的容错 1.1.服务雪崩 1.2.解决办法 2.hystrix 2.1.概述 2.2.项目结构及依赖 2.3.代码示例 2.3.1.注册中心 2.3.2.服务调用者 2.3.3.服务提供者 2.4.服务降级 2.4.1.单点响应 2.4.2.默认响应 2.4.3.前置响应 2.5.服务熔断 2.5.1.概述 2.5.2.使用…

centos 安装 nginx

1.下载nginx安装包 wget -c https://nginx.org/download/nginx-1.24.0.tar.gz 下载到了当前目录下 2.解压安装包 解压后的结果 3.安装依赖 yum -y install gcc gcc-c make libtool zlib zlib-devel openssl openssl-devel pcre pcre-devel 4. ./configure --prefix/usr/lo…

【Linux】深入理解文件系统

系列文章 收录于【Linux】文件系统 专栏 关于文件描述符与文件重定向的相关内容可以移步 文件描述符与重定向操作。 可以到 浅谈文件原理与操作 了解文件操作的系统接口。 想深入理解文件缓冲区还可以看看文件缓冲区。 目录 系列文章 磁盘 结构介绍 定位数据 抽象管理…

高速电路设计系列分享-电源噪声分析

文章目录 概要整体架构流程技术名词解释技术细节小结 概要 提示&#xff1a;这里可以添加技术概要 例如&#xff1a; 当今许多应用都要求高速采样模数转换器&#xff08;ADC)具有12位或以上的分辨率&#xff0c;以便用户能够进行更精确的系统测量。然而&#xff0c;更高分辨率…

【机器学习】机器故障的二元分类模型-Kaggle竞赛

竞赛介绍 数据集描述 本次竞赛的数据集&#xff08;训练和测试&#xff09;是从根据机器故障预测训练的深度学习模型生成的。特征分布与原始分布接近&#xff0c;但不完全相同。随意使用原始数据集作为本次竞赛的一部分&#xff0c;既可以探索差异&#xff0c;也可以了解在训…

使用CloudOS快速实现K8S容器化部署

关于容器技术 容器技术&#xff08;以docker和Kubernetes为代表&#xff09;呱呱坠地到如今&#xff0c;在国内经历了如下3个阶段&#xff1a; 婴儿期&#xff1a;2014-2016年的技术探索期&#xff1b; 少儿期&#xff1a;2017-2018年的行业试水期&#xff1b; 少年期&…
最新文章