0. 简介
由于 Spring Boot 采用了 "约定优于配置" 这种规范, 所以在使用静态资源的时候也很简单.
Spring Boot 对于静态资源用一种默认的约定.
resources/static: 放 js,CSS,image 等
resources/templates: 放 html 或者各种模板引擎的模板文件.
如果要使用 templates 首先要添加 templates 的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1. 访问 static 下的文件
在 static 下放一张图片, 名字为 spring-boot.jpg,
然后启动访问下:
http://localhost:9090/learning/spring-boot.jpg
2. 访问 templates 下的文件
由于 templates 下的文件是模板文件, 显示的时候需要数据的支持, 所以需要写固定的 controller 来访问. 我们在 templates 写个 helloSpring.html 文件, 内容如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Hello World</title>
- </head>
- <body>
- <div>
- hello spring!
- </div>
- </body>
- </html>
编写对应的 controller, 创建一个 PageController 类, 内容如下:
- /**
- * Create by ranzd on 2018/7/18
- *
- * @author cm.zdran@gmail.com
- */
- @Controller
- @RequestMapping("/page")
- public class PageController {
- @RequestMapping(value = "/helloSpring", method = RequestMethod.GET)
- public String getAccountByName() {
- return "helloSpring";
- }
- }
静态资源的访问好像不支持 RestController, 下面这种写法是访问不到页面的
- @RestController
- @RequestMapping("/page")
- public class PageController {
- @GetMapping("/helloSpring")
- public String getAccountByName() {
- return "helloSpring";
- }
- }
启动, 访问一下
http://localhost:9090/learning/page/helloSpring
3. html 引用 static 下的资源文件
下面我们将图片加入到 html 的页面中去.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Hello World</title>
- </head>
- <body>
- <div>
- <img src="/learning/images/spring-boot.jpg">
- </div>
- </body>
- </html>
html 中的路径是: 项目名 + static 下的目录. 当然你也可以理解为把 static 换成项目名就是 html 中的路径.
比如: 图片在项目中的路径是:
/static/images/spring-boot.jpg
那么在 html 中引用它的路径就是把 static 换成项目名:
/learning/images/spring-boot.jpg
这里说的项目名是指在 yaml 里配置的 context-path 不是代码的项目名称
4. 解决 thymeleaf 严格校验
在使用 thymeleaf 的时候经常出现的一个问题是:
- org.xml.sax.SAXParseException:
元素类型 "xxx" 必须由匹配的结束标记 "</xxx>" 终止.
这是因为 thymeleaf 对 html 代码进行了严格的校验. 解决办法有两个.
第一个比较简单, 就是把 终止标签补上就可以了.
第二个办法就是禁用严格校验. 下面说一下禁用方式.
以下解决方案参考自网络, 个人的建议还是直接补上结束标签
可以在 yaml 文件里添加一个配置
- spring:
- thymeleaf:
- mode: LEGACYHTML5
- cache: false
如果还是不行的话, 可以添加一下依赖
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.21</version>
</dependency>
如果还是不行, 就把结束标签补上吧, 别挣扎了.
来源: https://juejin.im/entry/5b4efc666fb9a04fac0d09e2