spring boot 笔记(四):返回静态页面
来源:互联网 发布:算法设计 pdf 编辑:程序博客网 时间:2024/05/29 11:20
Spring boot官方对于Thymeleaf模板提供了很好的支持,但默认不开通Thymeleaf模板,需要手动配置。
支持Thymeleaf模板
maven添加支持如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
application.properties添加如下配置:
# 定位模板的目录spring.mvc.view.prefix=classpath:/templates/# 给返回的页面添加后缀名spring.mvc.view.suffix=.html
controller返回页面:
@GetMapping("/index") public String index(){ return "home"; //当浏览器输入/index时,会返回 /templates/home.html页面 }
/templates下home.html页面如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"/> <link rel="stylesheet" type="text/css" href="/home.css"/> <title>home</title></head><body>home</body></html>
注意,spring boot默认开启了静态文件的配置,任何放在static文件夹下的资源都是静态文件。引用静态文件时以/
或者前缀不加任何定位符,都会去static文件夹下查找。
比如上面的home.html的代码,引用的css写法是: <link rel="stylesheet" type="text/css" href="/home.css"/>
则会去static文件夹下查找。
而<link rel="stylesheet" type="text/css" href="home.css"/>
这种写法则会定位到当前页面。
最后贴下resources的文件目录结构:
resources static home.css templates home.html
返回纯静态html
时下,比较流行的是前后端分离,前端做路由,前端的开发不使用模板。在这种情况下,使用模板就显得有些臃肿了。
spring boot返回静态页面的方式非常方便,首先需要移除maven的thymeleaf依赖。
非controller模式
这种模式不使用controller,将html和css,js同等对待。这种模式下,html中的如果不加/
,则会定位到当前页面。
要看到返回静态页面,只需要将之前的home.html移到static文件夹下。并删除controller和注释掉application.properties中的配置即可。直接在浏览器中输入:http://localhost:8080/index.html
。
controller模式
习惯上,我们还是多使用/index
方式,而不是index.html
方式。
为此还是需要controller。
# 定位页面的目录到static/下spring.mvc.view.prefix=/spring.mvc.view.suffix=.html
controller当然也是需要的,和之前一样:
@GetMapping("/index") public String index(){ return "home"; //当浏览器输入/index时,会返回 /static/home.html的页面 }
到这里就可以了。不在需要额外配置。在浏览器中输入:http://localhost:8080/index
就可以定位到static下的index.html页面了。
以上均为笔者亲测。
- spring boot 笔记(四):返回静态页面
- spring-boot笔记-静态资源及页面开发(六)
- spring boot 静态页面展示
- Spring Boot 系列(四)静态资源处理
- spring boot直接返回静态html
- Spring Boot---Web应用返回jsp页面
- spring boot security /error页面返回500
- [Spring boot] web应用返回jsp页面
- [Spring boot] web应用返回jsp页面
- Spring boot启动返回jsp页面
- [Spring boot] web应用返回jsp页面
- spring boot 返回jsp页面例子
- spring boot 学习笔记(005)返回json对象
- spring-boot笔记-HandlerInterceptor和MethodInterceptor(AspectJ)(四)
- Spring-Boot学习笔记(四)JDBC使用
- Spring Boot使用方法小札(1):Web应用返回jsp页面
- Spring Boot使用freemarker并且生成静态html页面
- Spring Boot学习(四)之web开发渲染页面 -- Thymeleaf
- java 怪胎之 String
- 堆排序,cpp实现
- 素数回文5到一亿
- axios资料整理
- ubuntu 14.04 LTS Docker安装(转载)
- spring boot 笔记(四):返回静态页面
- 深度学习:MATLAB 入门系列(一)
- css复习整理(一):选择器与创建
- Gerrit安装配置
- HDU 4763 Theme Section(kmp求前后缀)
- 说说函数中的极品-OFFSET
- undefined reference to symbol 'floor@@GLIBC_2.0'
- SQL学习笔记--限制于排序
- README.md 如何规范