在咱们开发Web应用的时候,须要引用大量的js、css、图片等静态资源。
Spring Boot的默认位置是resources/staticcss
各类模版的页面,此次咱们选用Thymeleaf
Spring Boot的默认位置是resources/templateshtml
在以前的示例中,咱们都是经过@RestController来处理请求,因此返回的内容为json对象。当咱们须要页面的时候使用@Controller,使其寻找模版页面java
对于已存在的项目能够在bulid.gradle加入git
compile('org.springframework.boot:spring-boot-starter-thymeleaf') compile('org.springframework.boot:spring-boot-starter-web')
至此Thymeleaf已经引入github
新建一个ThymeleafCtrl类web
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller//这是一个控制器 public class ThymeleafCtrl { @RequestMapping("/") public String hello(Model model) { model.addAttribute("hello","hello thymeleaf");//添加一个值为"hello thymeleaf"的hello变量到视图 return "hello";//在templates下寻找hello.html } }
在resources/templates建立一个hello.html页面spring
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"><!-- xmlns:th="http://www.thymeleaf.org" 减小ide报错,能够没有 --> <head> <meta charset="UTF-8"/> <title>Hello</title> </head> <body> <h1 th:text="${hello}">LieRabbit</h1><!-- 使用hello变量 --> <img src="lierabbit.jpg"/> </body> </html>
在resources/static添加lierabbit.jpgjson
更多的Thymeleaf的语法请前往官网查看文档(http://www.thymeleaf.org/doc/...)
源码地址:https://github.com/LieRabbit/...
原文地址:https://lierabbit.cn/2018/01/...app