Spring Boot从入门到精通-页面模板

时间:2022-06-21
本文章向大家介绍Spring Boot从入门到精通-页面模板,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在web大行其道的今天,有了接口之后最好的展示方式就是用页面。而Spring Boot中对于模板页有良好的支持。下面我们来介绍Spring Boot推荐的模板 thymeleaf。

  • 首先在pom.xml中加入依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

需要注意,为了让thymeleaf识别一个模板,你必须使用下面的html头标签:

<html xmlns:th="http://www.thymeleaf.org">
...
</html>
  • 引入javascript
<script th:inline="javascript">
 var article = [[${article}]];
...
</script>

首先我们在resources目录下新建templates文件夹和static文件夹。 关于这两个文件夹,在Spring Boot中,静态资源默认是访问resources下的static文件夹,动态html资源默认是访问resourcess目录下的templates。当然这两个默认路径可以再application.yml中进行配置,一般我们都使用默认路径。由于我们需要的是一个由Spring Boot生成的动态模板页,因此在templates下新建demo1.html。 由于动态模板页需要先经过后台接口,然后才返回一个html页面到前端,因此在controller文件夹下新建ThymeleafController.java。

@Controller
public class ThymeleafController {

    @GetMapping("/thymeleaf")
    public String testMapper() {
        return "demo1";
    }
}

注意我们使用了@Controller而不是@RestController。具体的区别请查看Spring Boot从入门到精通-注解详解。 写了一个路径为/thymeleaf的接口,该接口直接返回了一个值为我们需要返回的html的名字的字符串。 目录结构如下:

目录结构

  • 引入普通文本:th:text
<p th:text="'你好,thymeleaf~~~'"> hello world!</p>
  • 引入变量: ${变量名} 变量名由后台传递给前端,因此需要修改接口。
@GetMapping(value = "thymeleaf")
   public String articleInfo(Model model) {
       model.addAttribute("data", "i'm a data");
       User user = new User();
       user.setUserId(1);
       user.setUserName("admin");
       user.setPassword("123");
       user.setPhone("110");
       model.addAttribute("user", user);
       return "demo1";
   }

在方法上新增了一个入参model,通过model传递前端需要的值。而这个“data”就是前端的变量名。

<h1 th:text="'hello,' + ${data} + '!'">测试文本!</h1>
<h1 th:text="'标号:'+  ${user.userId}">id</h1>

另外也可以在JavaScript中直接使用对象接收。

  • 消息表达式:#{key} 消息表达式允许你再模板页面上读取消息源里面的静态内容,消息源可以是配置文件,数据库等,消息配置文件实际就是一个properties文件,文件内容为key=value形式的键值对。 如果你使用spring boot的默认配置,那么配置文件的名称为messages.properties,他必须放在resource根目录下,这样thymeleaf才能找到。 消息表达式常用于加载静态文本内容,之所以把静态内容提取为消息,是为了能方便的集中管理页面上某些可能会变动的内容。 在resources目录下新建messages.properties文件,加入配置:
home.data: i'm other data

html上的代码:

<h1 th:text="#{home.data}">你好,这是一条消息</h1>
  • 条件判断:if/unless
<p th:if="${user.userId} >= 1">用户的id大于1,于1,所以能显示这些</p>
<p th:unless="${user.userName == null }">当“用户名称为空”这个条件不成立就显示, 用户名为:<span th:text="${user.userName}">用户名</span></p>
  • 分支条件判断表达式:th:switch
<div th:switch="${user.userName}">
    <h1><p th:case="admin">他是管理员</p></h1>
    <h1><p th:case="admin2">这是第二个</p></h1>
    <h1><p th:case="*">你是游客</p></h1>
</div>
  • 基本内置对象:
  1. ctx:上下文对象。
  2. vars: 上下文变量。
  3. locale:上下文语言环境。
  4. request:(只在Web上下文中)HttpServletRequest对象。
  5. response:(只在Web上下文中)HttpServletResponse对象。
  6. session:(只在Web上下文中)HttpSession对象。
  7. servletContext:(只在Web上下文中)ServletContext对象。
你的操作系统语言环境为:
<span th:text="${#locale.language}"></span>,<span th:text="${#locale.displayCountry}"></span>,<span th:text="${#ctx.locale}"></span>