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

以上均为笔者亲测。

原创粉丝点击