spring boot thymeleaf简单使用

spring4推荐使用thymeleaf模板进行开发,刚好最近需要使用,一起来学习一下

1.加入maven依赖

<dependency>
   <groupId>net.sourceforge.nekohtml</groupId>
   <artifactId>nekohtml</artifactId>
   <version>1.9.22</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.简单配置application.yml

spring:
    thymeleaf:
            mode: LEGACYHTML5
            prefix: classpath:/templates/
            suffix: .html
            cache: false
            encoding: utf-8

3.编写html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<META HTTP-EQUIV="pragma" CONTENT="no-cache"> 
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"> 
<META HTTP-EQUIV="expires" CONTENT="0">
<head th:fragment="head">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>title</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet"  th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" href="//at.alicdn.com/t/font_tnyc012u2rlwstt9.css" media="all" />
    <link rel="stylesheet"  media="all" th:href="@{/css/main.css}"/>
    <script src="" th:src="@{/js/jquery-1.8.0.min.js}"></script>

    <script type="text/javascript">
        var WEB_ROOT = '[[${#httpServletRequest.contextPath}]]' + "/";
    </script>

</head>
<body>

</body>
</html>

我这里写的是一个简单的公共的html用到了th:fragment="head"用来定义用于加载的块,在我们需要使用的页面使用

<head th:replace="header :: head">就可以替换head标签里的内容,当然还可以使用th:include

th:include 和 th:replace的区别

th:include和th:replace都可以引入模块,两者的区别在于 
th:include:引入子模块的children,依然保留父模块的tag。 
th:replace:引入子模块的所有,不保留父模块的tag。

在js中还写了一串js代码,用来获取项目名

<script type="text/javascript"> var WEB_ROOT = '[[${#httpServletRequest.contextPath}]]' + "/"; </script>

这样的话需要在调后台服务的地方拼写WEB_ROOT就不用担心把路径搞错了

4.编写controller

@Controller
@RequestMapping("/test")
public class TestController {
    @RequestMapping("/toIndex")
    public String toIndex(){
        return "index";
    }
}

在controller里面返回视图就可以了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值