7.Spring Boot+Thymeleaf模板引擎开发Web应用

2019年04月11日 17:28 · 阅读(323) ·

[目录]

参考

本文参考了 Ken 的博客。结合自己的实际操作过程写成。

Spring Boot入门教程3-2、使用Spring Boot+Thymeleaf模板引擎开发Web应用

重要说明

本文中的编码是在 Spring Boot-1.构建第一个 Web 应用程序 这个例子上进行操作的

开发环境

名称 版本
操作系统 Windows 10 X64
JDK JDK1.8(jdk-8u151-windows-x64)
IntelliJ IDEA IntelliJ IDEA 2018.3
Maven Maven 3.6.0
Spring Boot 1.5.6

什么是 Spring Boot

Spring Boot 默认配置了很多框架的使用方式,整合了所有的框架

1.引入Thymeleaf

pom.xml 文件的 dependencies 引入

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  9. </dependency>
  10. </dependencies>

2.创建Thymeleaf模板

创建模板文件夹

resources 文件夹下新建 templates 文件夹,作为模板根目录

完整路径:src/main/resources/templates

templates 这个名词是 Spring Boot约定的,如果有需要,可以通过配置 application.yml 修改

  1. spring:
  2. thymeleaf:
  3. template-loader-path: classpath:/templates/

创建模板文件

templates 新建 welcome.html 文件

.ftl 就是 Thymeleaf 模板文件后缀,可以通过配置 application.yml 修改

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>欢迎页面</title>
  5. </head>
  6. <body>
  7. <h3 th:text="${message}"></h3>
  8. </body>
  9. </html>

使用 ${变量名} 可以输出 controller 中返回的对象

3.创建 Welcome 访问入口

HelloController 增加方法 welcome

  1. package com.my.luoma.springboot.course.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5. import org.springframework.web.servlet.ModelAndView;
  6. @Controller
  7. public class HelloController {
  8. @RequestMapping("/")
  9. @ResponseBody
  10. String index() {
  11. return "Hello World!";
  12. }
  13. @RequestMapping("/welcome")
  14. ModelAndView welcome(){
  15. ModelAndView model = new ModelAndView();
  16. model.setViewName("welcome");
  17. model.addObject("message","欢迎来到王者农药!");
  18. return model;
  19. }
  20. }

对比 index 函数,主要发生了以下几个变化:

1.去掉 @ResponseBody 注解,如果使用该注解,返回结果会直接输出,而不是使用模板引擎渲染

2.使用 ModelAndView 对象,指定视图名&添加视图对象

对于 setViewName 函数,如果视图的路径是templates/home/index.html

那么使用方式应该是:

  1. model.setViewName("home/index");

4.启动和访问

启动项目

使用快捷键 Shift+F10 启动即可

或者在 CourseApplication 编辑区,右键-运行-Spring Boot

访问项目

浏览器访问:http://localhost:8086/welcome

浏览器显示结果:

源码下载

见附件


相关附件 7.Spring Boot+Thymeleaf模板引擎开发Web应用 | 大小:0.04M | 下载