静态资源
在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
Spring Boot的默认位置是resources/static
模版页面
各种模版的页面,这次我们选用Thymeleaf
Spring Boot的默认位置是resources/templates
渲染页面
在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。当我们需要页面的时候使用@Controller,使其寻找模版页面
添加依赖
对于已存在的项目可以在bulid.gradle加入
compile('org.springframework.boot:spring-boot-starter-thymeleaf')compile('org.springframework.boot:spring-boot-starter-web')
至此Thymeleaf已经引入
创建控制器
新建一个ThymeleafCtrl类
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页面
Hello LieRabbit
添加图片资源
在resources/static添加lierabbit.jpg
运行结果
更多的Thymeleaf的语法请前往官网查看文档()
源码地址:
原文地址: