爬山的蜗牛旅程:三、springboot 整合Thymeleaf

学习springboot的旅程,就像蜗牛爬山,一点点的往上爬,一点点的欣赏旅途的风景

继续上一章的问题,在前后不分离的情况,你要怎么支持页面开发?

下面是页面模板引擎框架(随便挑----我瞎说的!)

  • Thymeleaf,FreeMarker,Enjoy,Velocity,JSP等

  • 它们之间的对比请参考:

  • 通过对比,你会发现:Thymeleaf性能是最低的,但是我还是选Thymeleaf(个人选择),当然你也可以根据你的需求去选择其它模板引擎。

    • 个人选择选择原因1:springboot官方推荐Thymeleaf
    • 个人选择选择原因2:可以在无网络的环境下运行(理解为静态html页面),也就是说可以在无环境的情况让前端开发静态html页面,从而达到前后解耦的境界。

springboot 整合Thymeleaf

  • 第一步:pom.xml引入Thymeleaf依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--需要注意的是,LEGACYHTML5需要搭配一个额外的库NekoHTML才可用。thymeleaf的依赖-->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>
  • 第二步:resources目录下创建templates,用来存放thymeleaf的html模板
    在这里插入图片描述
  • 第三步 在application.properties(application.ymx)配置thymeleaf文件目录的请求地址映射及格式编码信息
-----application.properties
#thymeleaf
#地址映射
spring.thymeleaf.prefix=classpath:/templates/
#指定后缀
spring.thymeleaf.suffix=.html
#指定模板类型
spring.thymeleaf.mode=LEGACYHTML5
#指定编码
spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type=text/html
#我设置为不缓存,true表示开启缓存
spring.thymeleaf.cache=false 	

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

这里加个题外话,application.properties和application.ymx的区别仅展示数据的结构不一样的

  • application.ymx:是按树层级结构展示配置数据的
  • application.properties:是按直观配置(每条配置都要写全配置参数名)

至此配置就完成了!

开始写模板例子

  • 编写html模板,在resources文件夹下创建templates文件夹,并创建index.html页面。
  • Templates更多用法
<!DOCTYPE html>   
    <html>
     <head>
          <meta charset="UTF-8"/>
          <title>index</title>
     </head>
     <body>
             <h1>Hello</h1>
     </body>
</html>
  • 编写controller层,请用标签@Controller,不是用@RestController,原因请看这
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//用这个注解--不是用@RestController
@RequestMapping("/test")
public class MyController {
    @RequestMapping("/test")
    public String test(){ 
        return "index";
    }
}

至此springboot整合Templates完毕,至于Templates更多用法,请出门左拐

好了,本章内容完毕!接下来的问题是:你在前后分离或不分离的情况下,要怎么管理和处理全局异常?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值