Skip to content

Commit 14115ae

Browse files
committed
Springboot 系列(五)web 开发之静态资源和模版引擎
1 parent b3bf328 commit 14115ae

1 file changed

Lines changed: 358 additions & 0 deletions

File tree

Lines changed: 358 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,358 @@
1+
---
2+
title: Springboot 系列(五)web 开发之静态资源和模版引擎
3+
toc_number: false
4+
date: 2019-02-15 22:32:01
5+
url: springboot/springboot-05-web-static-template
6+
tags:
7+
- Springboot
8+
- Thymelaf
9+
- FreeMarker
10+
categories:
11+
- Springboot
12+
---
13+
14+
## 前言
15+
Spring Boot 天生的适合 web 应用开发,它可以快速的嵌入 Tomcat, Jetty 或 Netty 用于包含一个 HTTP 服务器。且开发十分简单,只需要引入 web 开发所需的包,然后编写业务代码即可。
16+
17+
## **自动配置原理?**
18+
19+
在进行 web 开发之前让我再来回顾一下自动配置,可以参考系列文章第三篇。Spring Boot 为 Spring MVC 提供了自动配置,添加了如下的功能:
20+
21+
- 视图解析的支持。
22+
- 静态资源映射,WebJars 的支持。
23+
- 转换器 Converter 的支持。
24+
- 自定义 Favicon 的支持。
25+
- 等等
26+
<!-- more -->
27+
在引入每个包时候我们需要思考是如何实现自动配置的,以及我们能自己来配置哪些东西,这样开发起来才会得心应手。
28+
29+
[关于 Spring Boot Web 开发的更详细介绍可以参考官方文档。](https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/boot-features-developing-web-applications.html)
30+
31+
## 1. JSON 格式转换
32+
33+
Spring Boot 默认使用 Jackson 进行 JSON 化处理,如果想要切换成 FastJson 可以首先从[官方文档](https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/howto-spring-mvc.html#howto-customize-the-responsebody-rendering)里查询信息。从这里知道对于 ResponseBody 的渲染主要是通过 HttpMessageConverters, 而首先引入FastJson Pom依赖并排除 Spring Boot 自带的 Jackson。
34+
35+
```xml
36+
<dependency>
37+
<groupId>org.springframework.boot</groupId>
38+
<artifactId>spring-boot-starter-web</artifactId>
39+
<exclusions>
40+
<exclusion>
41+
<artifactId>spring-boot-starter-json</artifactId>
42+
<groupId>org.springframework.boot</groupId>
43+
</exclusion>
44+
</exclusions>
45+
</dependency>
46+
<dependency>
47+
<groupId>com.alibaba</groupId>
48+
<artifactId>fastjson</artifactId>
49+
<version>1.2.47</version>
50+
</dependency>
51+
```
52+
53+
编写转换器处理 json 的日期格式同时处理中文乱码问题。
54+
55+
```java
56+
@Configuration
57+
public class WebMvcConfig implements WebMvcConfigurer {
58+
59+
/**
60+
* 自定义JSON转换器
61+
*
62+
* @param converters
63+
*/
64+
@Override
65+
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
66+
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
67+
FastJsonConfig fastJsonConfig = new FastJsonConfig();
68+
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
69+
//日期格式化
70+
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
71+
//处理中文乱码问题
72+
List<MediaType> fastMediaTypes = new ArrayList<>();
73+
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
74+
75+
converter.setSupportedMediaTypes(fastMediaTypes);
76+
converter.setFastJsonConfig(fastJsonConfig);
77+
78+
converters.add(converter);
79+
}
80+
81+
}
82+
```
83+
84+
## 2. 静态资源映射
85+
86+
> By default, Spring Boot serves static content from a directory called `/static` (or `/public` or `/resources` or `/META-INF/resources`) in the classpath or from the root of the `ServletContext`.
87+
### 2.1 默认映射
88+
官方文档告诉我们 Spring Boot 对于静态资源的映射目录是 /static , /public , /resources 以及 /META-INF/resource。除此之外其实还映射了 `/webjars/**``classpath:/META-INF/resources/webjars`
89+
90+
很明显此处是自动配置实现的,通过查看源码分析这段配置。
91+
92+
![Mvc静态资源映射](https://cdn.jsdelivr.net/gh/niumoo/cdn-assets/2019/746f53d54281496bb8aafcc2e7f1ada6.png)
93+
94+
![Mvc静态资源映射](https://cdn.jsdelivr.net/gh/niumoo/cdn-assets/2019/03afb17acb7e7a3ccd45a5b434f111d1.png)
95+
96+
而对于网站图标,Spring Boot 也已经配置了默认位置,可以在看到。
97+
98+
```java
99+
// path: org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
100+
@Bean
101+
public SimpleUrlHandlerMapping faviconHandlerMapping() {
102+
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
103+
mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
104+
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", // 图表
105+
faviconRequestHandler()));
106+
return mapping;
107+
}
108+
109+
@Bean
110+
public ResourceHttpRequestHandler faviconRequestHandler() {
111+
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
112+
requestHandler.setLocations(resolveFaviconLocations());
113+
return requestHandler;
114+
}
115+
116+
private List<Resource> resolveFaviconLocations() {
117+
String[] staticLocations = getResourceLocations(
118+
this.resourceProperties.getStaticLocations());
119+
List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
120+
Arrays.stream(staticLocations).map(this.resourceLoader::getResource)
121+
.forEach(locations::add);
122+
locations.add(new ClassPathResource("/"));
123+
return Collections.unmodifiableList(locations);
124+
}
125+
```
126+
127+
根据 Spring Boot 默认的静态资源映射规则,可以直接把需要的静态资源放在响应的文件夹下然后直接引用即可。
128+
129+
![静态资源映射](https://cdn.jsdelivr.net/gh/niumoo/cdn-assets/2019/4d1f6c2368dce288a2187741fc4dc0c7.png)
130+
131+
而放在 Public 文件夹下的 HTML 页面也可以直接访问。
132+
![静态资源映射](https://cdn.jsdelivr.net/gh/niumoo/cdn-assets/2019/79377b2dadbeee45f00da8921190938b.png)
133+
134+
### 2.2 webjars
135+
136+
[webjars](https://www.webjars.org/) 的思想是把静态资源打包到 Jar 包中,然后使用 JVM 构建工具进行管理,如 maven , Gradle 等。
137+
138+
使用 webjars 第一步需要进入依赖,如要使用 bootstrap。
139+
140+
```xml
141+
<!-- Web Jars 静态资源文件 -->
142+
<dependency>
143+
<groupId>org.webjars</groupId>
144+
<artifactId>bootstrap</artifactId>
145+
<version>4.1.3</version>
146+
</dependency>
147+
```
148+
149+
引入之后查看 bootstrap 资源。
150+
151+
![WebJars 引入 bootstrap](https://cdn.jsdelivr.net/gh/niumoo/cdn-assets/2019/3626437cd5104cea9ed5a82ea25aac0c.png)
152+
153+
由于 Springboot 映射了 `/webjars/**``classpath:/META-INF/resources/webjars`. 因此可以直接在文件中引用 webjars 的静态资源。
154+
155+
```html
156+
<!-- Bootstrap core CSS -->
157+
<link href="/webjars/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
158+
<script src="/webjars/bootstrap/4.1.3/js/bootstrap.min.js"></script>
159+
```
160+
161+
162+
163+
## 3. 模版引擎
164+
165+
Spring MVC 支持各种模版技术,如 Thymeleaf , FreeMarker , JSP 等。而Thyemeleaf 原型即页面的特性或许更符合 Spring Boot 快速开发的思想而被官方推荐。
166+
167+
![模版引擎原理](https://cdn.jsdelivr.net/gh/niumoo/cdn-assets/2019/02c76ef91580600fb7265155822d5619.png)
168+
169+
[Thymeleaf](https://www.thymeleaf.org/) 是适用于 Web 开发的服务端 Java 模版引擎,Thymeleaf 为开发工作流程带来优雅自然的模版,由于其非侵入的特性,可以让页面不管是在静态原型下还是用作模版引擎时都有良好的页面展现。
170+
171+
```html
172+
<table>
173+
<thead>
174+
<tr>
175+
<th th:text="#{msgs.headers.name}">Name</th>
176+
<th th:text="#{msgs.headers.price}">Price</th>
177+
</tr>
178+
</thead>
179+
<tbody>
180+
<tr th:each="prod: ${allProducts}">
181+
<td th:text="${prod.name}">Oranges</td>
182+
<td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
183+
</tr>
184+
</tbody>
185+
</table>
186+
```
187+
188+
### 3.1 引入 Thymeleaf
189+
190+
```xml
191+
<!-- thymeleaf 模版-->
192+
<dependency>
193+
<groupId>org.springframework.boot</groupId>
194+
<artifactId>spring-boot-starter-thymeleaf</artifactId>
195+
</dependency>
196+
```
197+
198+
### 3.2 使用 Thymeleaf
199+
200+
根据 Spring Boot 自动配置原理,先看一下 Thymeleaf 的配置类,从中可以看出 Thymeleaf 的相关配置。我们可以知道 默认存放目录是 templates 文件夹,文件后缀为 `.html` 且开启了缓存。
201+
202+
```java
203+
@ConfigurationProperties(prefix = "spring.thymeleaf")
204+
public class ThymeleafProperties {
205+
206+
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
207+
208+
public static final String DEFAULT_PREFIX = "classpath:/templates/";
209+
210+
public static final String DEFAULT_SUFFIX = ".html";
211+
/**
212+
* Whether to enable template caching.
213+
*/
214+
private boolean cache = true;
215+
```
216+
217+
为了在开发中编写模版文件时不用重启,可以在配置中关闭缓存。
218+
219+
```properties
220+
# 关闭模版缓存
221+
spring.thymeleaf.cache=false
222+
# 如果需要进行其他的配置,可以参考配置类:ThymeleafProperties
223+
# org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
224+
```
225+
226+
编写 Controller 响应信息。
227+
228+
```java
229+
/**
230+
* 获取ID为1的用户信息
231+
*
232+
* @return
233+
*/
234+
@GetMapping(value = "/user/1")
235+
public String getUserById(Model model) {
236+
User user1 = new User("Darcy", "password", 24, new Date(), Arrays.asList("Java", "GoLang"));
237+
User user2 = new User("Chris", "password", 22, new Date(), Arrays.asList("Java", "Web"));
238+
ArrayList<User> userList = new ArrayList<>();
239+
userList.add(user1);
240+
userList.add(user2);
241+
model.addAttribute("userList", userList);
242+
model.addAttribute("user", user1);
243+
return "user";
244+
}
245+
```
246+
247+
因为 Thymelaf 默认模版位置在 templates 文件夹下,因此在这个文件夹下编写页面信息。
248+
249+
```html
250+
<!doctype html>
251+
<html lang="en" xmlns:th="http://www.thymeleaf.org">
252+
<head>
253+
<title>Thymeleaf 的基本使用</title>
254+
<!-- 引入JS文件 -->
255+
<!--<script th:src="@{/static/js/alert.js}"></script>-->
256+
</head>
257+
<body>
258+
259+
<div>
260+
<p><b>Hello Thymeleaf Index</b></p>
261+
用户名称:<input th:id="${user.username}" th:name="${user.username}" th:value="${user.username}">
262+
<br/>
263+
用户技能:<input th:value="${user.skills}">
264+
<br/>
265+
用户年龄:<input th:value="${user.age}">
266+
<br/>
267+
用户生日:<input th:value="${#dates.format(user.birthday,'yyyy-MM-dd hh:mm:ss ')}">
268+
</div>
269+
270+
271+
<div th:object="${user}">
272+
<p><b>Hello Thymeleaf Index</b></p>
273+
274+
用户名称:<input th:id="*{username}" th:name="*{username}" th:value="*{username}">
275+
<br/>
276+
用户技能:<input th:value="*{skills}">
277+
<br/>
278+
用户年龄:<input th:value="*{age}">
279+
<br/>
280+
用户生日:<input th:value="*{#dates.format(birthday,'yyyy-MM-dd hh:mm:ss')}">
281+
</div>
282+
283+
<div>
284+
<p><b>Text 与 utext</b></p>
285+
<!-- th:text 显示HTML源码,作为字符串 -->
286+
<span th:text="${user.username}">abc</span>
287+
<br>
288+
<span th:utext="${user.username}">abc</span>
289+
</div>
290+
291+
<div>
292+
<p><b>URL 的引用</b></p>
293+
<a th:href="@{https://www.baidu.com}">网站网址</a>
294+
</div>
295+
296+
<div>
297+
<p><b>表单的使用</b></p>
298+
<form th:action="@{/th/postform}" th:object="${user}" method="post">
299+
用户名称:<input type="text" th:field="*{username}">
300+
<br/>
301+
用户技能:<input type="text" th:field="*{skills}">
302+
<br/>
303+
用户年龄:<input type="text" th:field="*{age}">
304+
<input type="submit">
305+
</form>
306+
</div>
307+
308+
<div>
309+
<p><b>判断的使用</b></p>
310+
<div th:if="${user.age} == 18">18岁了</div>
311+
<div th:if="${user.age} gt 18">大于18</div>
312+
<div th:if="${user.age} lt 18">小于18</div>
313+
<div th:if="${user.age} ge 18">大于等于</div>
314+
<div th:if="${user.age} le 18">小于等于</div>
315+
</div>
316+
317+
<div>
318+
<p><b>选择框</b></p>
319+
<select>
320+
<option>请选择一本书</option>
321+
<option th:selected="${user.username eq 'admin'}">管理员</option>
322+
<option th:selected="${user.username eq 'Darcy'}">Darcy</option>
323+
<option th:selected="${user.username eq 'Chris'}">Chris</option>
324+
</select>
325+
</div>
326+
327+
<div>
328+
<p><b>遍历功能</b></p>
329+
<table>
330+
<tr>
331+
<th>用户名称</th>
332+
<th>年龄</th>
333+
<th>技能</th>
334+
</tr>
335+
<tr th:each="u:${userList}">
336+
<td th:text="${u.username}"></td>
337+
<td th:text="${u.age}"></td>
338+
<td th:text="${u.skills}"></td>
339+
</tr>
340+
</table>
341+
</div>
342+
343+
<div>
344+
<p><b>Switch功能</b></p>
345+
<div th:switch="${user.username}">
346+
<p th:case="'admin'">欢迎管理员</p>
347+
</div>
348+
</div>
349+
</body>
350+
</html>
351+
```
352+
访问页面可以看到数据正常显示。
353+
354+
![访问页面](https://cdn.jsdelivr.net/gh/niumoo/cdn-assets/2019/5e7b0da4afded072ed59c42a34b3f7fc.png)
355+
356+
文章代码已经上传到 GitHub [Spring Boot Web开发 - 静态资源](https://github.com/niumoo/springboot/tree/master/springboot-web-staticfile)。
357+
文章代码已经上传到 GitHub [Spring Boot Web开发 - 模版引擎](https://github.com/niumoo/springboot/tree/master/springboot-web-template)。
358+

0 commit comments

Comments
 (0)