Spring Boot 学习笔记(五) 整合 静态资源

1,844 阅读3分钟

Spring Boot 学习笔记(五) 整合 静态资源


0. 简介

由于 Spring Boot 采用了”约定优于配置”这种规范,所以在使用静态资源的时候也很简单。

Spring Boot 对于静态资源用一种默认的约定。

1resources/static: 放js、css、image等
2resources/templates: 放 html 或者各种模板引擎的模板文件。

如果要使用 templates 首先要添加 templates的依赖

1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-thymeleaf</artifactId>
4</dependency>

1. 访问static下的文件

在 static 下放一张图片, 名字为 spring-boot.jpg,

然后启动访问下:http://localhost:9090/learning/spring-boot.jpg

2. 访问templates下的文件

由于templates下的文件是模板文件,显示的时候需要数据的支持,所以需要写固定的controller来访问。我们在templates写个helloSpring.html文件,内容如下:

1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <title>Hello World</title>
6</head>
7<body>
8    <div>
9        hello spring!
10    </div>
11</body>
12</html>

编写对应的controller,创建一个PageController类,内容如下:

1/**
2 * Create by ranzd on 2018/7/18
3 *
4 * @author cm.zdran@gmail.com
5 */
6@Controller
7@RequestMapping("/page")
8public class PageController {
9
10    @RequestMapping(value = "/helloSpring", method = RequestMethod.GET)
11    public String getAccountByName() {
12        return "helloSpring";
13    }
14}
15

静态资源的访问好像不支持RestController,下面这种写法是访问不到页面的

1@RestController
2@RequestMapping("/page")
3public class PageController {
4
5    @GetMapping("/helloSpring")
6    public String getAccountByName() {
7        return "helloSpring";
8    }
9}

启动,访问一下 http://localhost:9090/learning/page/helloSpring

3. html 引用 static下的资源文件

下面我们将图片加入到html的页面中去。

1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <title>Hello World</title>
6</head>
7<body>
8    <div>
9        <img src="/learning/images/spring-boot.jpg">
10    </div>
11</body>
12</html>

html中的路径是:项目名 + static 下的目录。当然你也可以理解为把static换成项目名就是html中的路径。

比如:图片在项目中的路径是: /static/images/spring-boot.jpg那么在html中引用它的路径就是把 static换成项目名:/learning/images/spring-boot.jpg

这里说的项目名是指在yaml里配置的 context-path 不是代码的项目名称

4. 解决thymeleaf严格校验

在使用 thymeleaf 的时候经常出现的一个问题是:

1org.xml.sax.SAXParseException: 
2
3元素类型 "xxx" 必须由匹配的结束标记 "</xxx>" 终止。 

这是因为 thymeleaf 对html代码进行了严格的校验。解决办法有两个。

第一个比较简单,就是把 终止标签补上就可以了。

第二个办法就是禁用严格校验。下面说一下禁用方式。

以下解决方案参考自网络,个人的建议还是直接补上结束标签

可以在 yaml 文件里添加一个配置

1spring:
2  thymeleaf:
3    mode: LEGACYHTML5
4    cache: false

如果还是不行的话,可以添加一下依赖

1<dependency>
2    <groupId>net.sourceforge.nekohtml</groupId>
3    <artifactId>nekohtml</artifactId>
4    <version>1.9.21</version>
5</dependency>

如果还是不行,就把结束标签补上吧,别挣扎了。

转载请注明出处
本文链接:zdran.com/20180718.ht…