spring boot 笔记(四):返回静态页面

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页面了。

以上均为笔者亲测。

评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值