java后端开发第四篇:springboot中thymeleaf入门

thymeleaf是springboot中所支持的一种模板引擎。入门级使用如下:

  1. pom.xml中引入依赖:
 <!-- 引入模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2.application.yml中根据情况添加配置:

 thymeleaf:
    cache: false #开发过程中建议关闭cache
    encoding: UTF-8  #thymeleaf编码
    suffix: .html #thymeleaf后缀
    servlet:
      content-type: text/html

3.在项目的templates目录下新建要显示的模板界面custom.html文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot之thymeleaf</title>
</head>
<body>
<h1>学习thymeleaf!</h1>

<hr width="300" align="left">

<div th:text="${hello}"></div> <!--th:text,显示时会把html对应的标签显示出来-->

<hr width="300" align="left">

<div th:utext="${hello2}"></div> <!--th:text,显示时不会把html对应的标签显示出来-->

<hr width="300" align="left">

<h4 th:text="${user}" th:each="user:${users}"></h4><!--th:eachg对传入的数组进行遍历-->

<hr width="300" align="left">

<h4>
    <span th:each="student:${students}">[[${student}]]  </span> <!--[]转义特殊字符-->
</h4>
</body>
</html>

4.controller中编写代码,给模板中添加相应数据


@Controller
public class IndexController {

    @RequestMapping("/custom")
    public String success(Map<String,Object> map){
        map.put("hello","<h2>我的第一节课</h2>");
        map.put("hello2","<h2>不会显示h2标签</h2>");
        map.put("users", Arrays.asList("张三","李四","王五"));
        map.put("students", Arrays.asList("王琴","陈军","郭大伟","陈明"));
        return "custom";
    }
}

5.浏览器中测试,访问http://localhost:8080/custom,结果如下:
在这里插入图片描述
6.开始时,在controller中一个疏忽点,写错了注解,把@Controller写成了@RestController,结果显示就如下了。
在这里插入图片描述
备注:@RestController=@ResponseBody + @Controller

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值