前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何将Thymeleaf技术集成到SpringBoot项目中

如何将Thymeleaf技术集成到SpringBoot项目中

作者头像
愿天堂没有BUG
发布2022-10-28 15:51:49
1.1K0
发布2022-10-28 15:51:49
举报
文章被收录于专栏:愿天堂没有BUG(公众号同名)

给天气预报一个“面子”

截至目前,不仅有了天气预报的API接口,也有了数据的缓存方案。现在,就要进行天气预报服务的实现,也就是说,这里需要一个面向用户的应用。这个应用应该拥有友好的界面,而不是一堆难以理解的数据。

天气预报服务将会引入前端的知识内容。下面将演示如何来将Thymeleaf技术框架集成到Spring Boot项目中。

在micro-weather-quartz应用的基础上,新建一个名称为micro-weather-report的应用。

所需环境

为了演示本例,需要采用如下开发环境。

  • .JDK8。
  • . Gradle 4.0。
  • . Spring Boot Web Starter 2.0.0.M4。
  • Apache HttpClient 4.5.3。
  • . Spring Boot Data Redis Starter 2.0.0.M4。
  • Redis 3.2.100。
  • . Spring Boot Quartz Starter 2.0.0.M4。
  • .Quartz Scheduler 2.3.0。
  • Spring Boot Thymeleaf Starter 2.0.0.M4。
  • Thymeleaf 3.0.7.RELEASE。
  • .Bootstrap 4.0.0-beta.2。

项目配置

下面需要添加Thymeleaf的依赖。Spring Boot Thymeleaf Starter已经提供了相关的Starter来实现Thymeleaf开箱即用的功能,所以只需要在build.gradle文件中添加Spring Boot Thymeleaf Starter的库即可。

代码语言:javascript
复制
//依赖关系
dependencies {
//...
//添加Spring Boot Thymeleaf Starter的依赖
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
//...
}

天气预报服务的需求

为了要实现某个服务的功能,首先需要了解这个服务所有的业务需求。天气预报服务的需求大概有以下几点。

·天气预报服务可以按照不同的城市来进行查询。

。天气预报服务可以查询近几天的天气信息。

。天气预报服务提供了天气预报的直观查询,其界面简洁、优雅(这点涉及用户体验)。

在了解上述需求之后,我们能够快速地设计出应用的API。

GET /report/cityId/{cityId}

该API非常简单,通过传入cityld就能获取到该城市的天气预报信息。

天气预报服务接口及其实现

在 com.waylau.spring.cloud.weather.service包下,创建天气预报服务接口WeatherReportService。

代码语言:javascript
复制
public interface WeatherReportService {
**
*根据城市ID查询天气信息
*
*@param cityId
*@return
*/
weather getDataByCityld(String cityId);}

WeatherReportService的实现为WeatherReportServiceImpl。

代码语言:javascript
复制
@Service
public class WeatherReportServiceImpl implements WeatherReportService
@Autowired
private WeatherDataService weatherDataServiceImpl;
@override
public Weather getDataByCityId(String cityId) {
WeatherResponse result = weatherDataServiceImpl.getDataByCityId
(cityId);
return result.getData();
                      }
}

WeatherReportServiceImpl主要依赖于WeatherDataService来提供天气数据服务。

这样,天气预报的服务接口就完成了。整体实现还是比较简单的。

控制层实现

控制层主要用于处理用户的请求。当用户访问/report/cityId/{cityld}接口时,返回用于展示天气预报信息的界面。

控制层实现如下。

代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.waylau.spring.cloud.weather.service.cityDataService;
import com.waylau.spring.cloud.weather.service.WeatherReportService;
/**
*天气预报API.
*
* @since 1.o.0 2017年10月25日
*author <a href="https://waylau.com">Way Lau</a>
*/
@RestController
@RequestMapping("/report")
public class WeatherReportController {
@Autowired
private CityDataService cityDataService;
@Autowired
private WeatherReportService weatherReportService;
@GetMapping("/cityld/{cityId}")
public ModelAndView getReportByCityId(Pathvariable("cityId")String
cityId,Model model) throws Exception{
model.addAttribute("title","老卫的天气预报");
model.addAttribute("cityId",cityId);
model.addAttribute("cityList",cityDataService.listCity());
model.addAttribute("report",weatherReportService.getDataByCity
Id(cityId));
return new ModelAndView ("weather/report", "reportModel",model);
}

WeatherReportController是一个典型的Spring MVC 的使用。在weather/report页面中绑定相应的模型,最终将模型的数据在该页面中展示。

在该reportModel中,存放了4类数据。

.title:用于展示页面的标题。

. cityId:用于绑定当前所访问城市的ID。

.cityList:依赖于CityDataService来提供城市列表的数据。

.report:依赖于WeatherReportService来提供当前所访问城市的天气预报。

编写前台界面

一款好的应用离不开简洁的界面。毕竟最终与用户打交道的就是界面,而不是后台的数据或服务。

下面使用Thymeleaf来作为前台界面的模板引擎,用Bootstrap来实现响应式的布局及页面的美化。

1.配置 Thymeleaf

在开发过程中,我们希望对于页面的编写能够及时反馈到界面上,这就需要设置模板。在Thymeleaf中,只需将Thymeleaf缓存关闭,就能够实现页面的热拔插(热部署)。

在application.properties文件中,只需设置如下选项即可。

代码语言:javascript
复制
#热部署静态文件
spring.thymeleaf.cache=false

2.页面实现

整体的页面实现如下。

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>老卫的天气预报(waylau.com)</title>
<meta charset="ut-8">
<meta name="viewport"
content="width=device-width,initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/
bootstrap.min.css"
integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE
4W1pov HYgTpBfshb"
crossorigin="anonymous"
/head>
<body>
<div class="container"
<div class="row"
h3 th:text="${reportModel.title}">waylau/h3>
<select id-"selectCityId">
<option th:each="city :${reportModel.cityList}"
th:value="${city.cityId}" th:text="${city.cityName}"
th:selected="${city.cityId eq reportModel.cityId}"
>Volvo</option>
</select>
</div>
<div class="row">
<hl th:text="${reportModel.report.city}"></h1>
</div>
<divclass="row">
<p>
空气质量指数:<span th:text="${reportModel.report.aqi}"></
span>
</p>
</div>
<div class="row"
<p>
当前温度:<span th:text="${reportModel.report.wendu}"></
span>
/p
</div>
<div class="row">
<p>
温馨提示:<span th:text="${reportModel.report.ganmao}"></
span>
</p>
</div>
<divclass="rOw"
<div class="card" th:each="forecast:${reportModel.report.
forecast}">
<div class="card-body"
<p class="card-text" th:text="${forecast.date}">周五</p>
<p class="card-text" th:text="${forecast.type}">晴转
多云</p>
<p class="card-text" th:text="${forecast.high}">高温
28℃</p>
<p class="card-text" th:text="${forecast.low}">低温
21℃</p>
<p class="card-text" th:text="${forecast.fengxiang}"
>无持续风向微风</p>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJw
FDMVNA/GpGFF93hxpG5KkN"
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/
umd/popper.min.js"
integrity="sha384-VFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLE
a04IHwicKwpJf9c91pFgh"
crossorigin="anonymous"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/
bootstrap.min.js"
integrity="sha384-alpBpkhlPFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5i
KTfUKjNkCk9SaVuEZflJ"
crossorigin="anonymous"></script>
</body>
</html>

在页面的头部,我们引入了Bootstrap的CSS文件,在页面的底部,引入了Bootstrap及其所依赖的jQuery和Popper等JS文件。其中,这些文件都是采用CDN服务的方式来引入的。如果读者有兴趣,也可以手动下载这些文件,将其放置到应用中。

在这个界面中,我们主要应用了以下几个技术点。

  • . Thymeleaf迭代器。

th:each将循环array或list中的元素并重复打印一组标签,语法相当于Java foreach表达式。在th:each="city : S{reportModel.cityList}"语句中,city是城市列表中的城市信息元素变量。通过这个元素变量,可以很方便地将该变量中的信息获取出来,比如${city.cityld}就是获取该变量的cityld。

  • Thymeleaf比较。

eq是一个比较两个元素是否相等的运算符。

在th:selected="S{city.cityld eq reportModel.cityld},"例子中,用户试图通过比较当前迭代器中cityld与访问请求时的cityld是否相等,来决定selected 的值。如果相等,就选中。就是为了在初始化下来的列表时,能够默认选中所要请求的城市。

  • . Bootstrap 的Card组件。

下面使用了最新版本的Bootstrap 样式,与老版本的Bootstrap 相比,新版Bootstrap新增了Card组件。

Card 是一个灵活可扩展的内容容器,它包括页眉和页脚的选项,可以设置各种内容、上下文背景颜色等。

用户使用Card来制作天气预报的信息块,这样天气预报中未来5天的每一天的信息,都能够放在一个块内。

其他样式,包括text-success和 border-info等都是用于设置边框字体的颜色样式的。

3.选择城市

用户可以利用城市下拉列表来触发请求。通过下拉列表选择不同的城市,来获取不同城市的天气信息。

下面需要一段JS脚本来驱动这个事情。

代码语言:javascript
复制
//DOM加载完再执行
$(function(){
$("#selectCityId").change(function(){
var cityId=$("#selectcityId").val();//获取select选择的Value
var url ='/report/cityId/'+cityId;
window.location.href= url;
});
});

脚本非常简单,当下拉列表变动时,就能把相应的选中的城市ID给获取到,从而重定向请求到/report/cityId/{cityld}接口。

JS脚本既可以放在HTML页面中,也可以放置在独立的JS文件中。为了便于管理,这里把该脚本放置到resources/static/js目录下的report.js文件中,同时,在页面里面引用该JS文件。

代码语言:javascript
复制
<script th:srC="C{/js/weather/report.js}"></script>

测试应用

在启动应用之前,需要保证Redis服务已经先启动了。

启动应用之后,通过浏览器访问 http:/localhost:8080/report/cityId/101280601页面,就能看到如下的页面效果,如图6-6所示。

同时,通过单击城市下拉列框来查看不同城市的天气情况。

本篇内容讲解的是如何将Thymeleaf技术集成到SpringBoot项目中

  1. 下篇文章给大家讲解如何进行微服务的拆分;
  2. 觉得文章不错的朋友可以转发此文关注小编;
  3. 感谢大家的支持!!

本文就是愿天堂没有BUG给大家分享的内容,大家有收获的话可以分享下,想学习更多的话可以到微信公众号里找我,我等你哦。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-05-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 愿天堂没有BUG 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 给天气预报一个“面子”
  • 所需环境
  • 项目配置
  • 天气预报服务的需求
  • 天气预报服务接口及其实现
  • 控制层实现
  • 编写前台界面
  • 测试应用
  • 本篇内容讲解的是如何将Thymeleaf技术集成到SpringBoot项目中
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档