天天看点

Springboot 静态资源路径配置 实例介绍

这里主要介绍使用yml去配置静态资源路径,会由简单慢慢到详细地去介绍怎么使用yml来配置静态资源

示例:

单独配置了静态资源的访问路径  ,这个配置项相当于重新定义该项目的静态资源文件夹路径

spring:
  resources:
    static-locations: classpath:html/      

然后咱们在resources文件夹路径下,新建文件夹html ,放入一个简单的页面testPage.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>hello~</h1>

</body>
</html>      

目录路径: 

Springboot 静态资源路径配置 实例介绍

 接下来,我们编写一个简单的接口,访问我们上面配置的静态资源 testPage.html:

@Controller
public class TestController {
    @GetMapping("/test")
    public String test() {
        System.out.println("方法已经访问到了!");

        return "testPage.html";
    }

}      

结果:

Springboot 静态资源路径配置 实例介绍

可以看到我们的页面是访问成功了,在这时候我们把一张图片  testImage.jpg 放到这个刚刚新建的静态资源文件夹 html里面:

Springboot 静态资源路径配置 实例介绍

再重启 ,访问​​http://localhost:8091/testImage.jpg​​ :

(可以看到这个静态资源读取是肯定没有问题了)

Springboot 静态资源路径配置 实例介绍

 记下来,我们一起来优化一下接口访问html的编码,也就是不需要在返回的内容里面加 .html  :

Springboot 静态资源路径配置 实例介绍

那么我们就需要用到新的配置项,前后缀的配置 :

spring:
  resources:
    static-locations: classpath:html/
  mvc:
    view:
      suffix: .html
      prefix:      

因为我们这里html在resources文件夹下面的第一级目录,所以不需要配置前缀,只配置后缀 .html   

然后我们把接口改成:

@GetMapping("/test")
    public String test() {
        System.out.println("方法已经访问到了!");
        return "testPage";
    }      

重启项目,访问接口,结果:

Springboot 静态资源路径配置 实例介绍

OK,这样已经在访问静态资源上比较完善了。

接下来,还需要讲一个配置项,静态资源寻址拦截匹配(规则)  static-path-pattern:,

spring:
  resources:
    static-locations: classpath:html/
  mvc:
    view:
      suffix: .html
      prefix: 
    static-path-pattern: /JCccc/**      

 可以看到我添加的规则是 /JCccc/**  ,这个意思是,就算项目在找静态资源的时候,优先回去校验访问路径是否符合规则,

只有符合规则的路径,才继续帮它去寻找相关的静态资源。

那么,我们添加完这个配置项后,我们重启项目,访问接口:

Springboot 静态资源路径配置 实例介绍

可以看到,其实接口已经访问到了,但是在最后返回html页面时,匹配规则没有符合,所以返回了 404.

那么我们需要做出对应的更改:

@GetMapping("/test")
    public String test() {
        System.out.println("方法已经访问到了!");
        return "JCccc/testPage";
    }      

OK,重启项目,访问接口:

Springboot 静态资源路径配置 实例介绍

到了这里,其实关于springboot静态资源的yml配置介绍,其实都玩了一遍。

那么最后,试着在的testPage.tml页面,加上一个在该页面上访问静态资源图片,作为最后一个小例子:

我们先在static文件夹下,创建文件夹image,里面放入图片image100.jpg:

Springboot 静态资源路径配置 实例介绍

然后在yml里面添加该路径为静态资源路径:

spring:
  resources:
    static-locations: classpath:html/,classpath:static/
  mvc:
    view:
      suffix: .html
      prefix:
    static-path-pattern: /JCccc/**      

然后修改下testPage.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello~</h1>
<img src="JCccc/image/image100.jpg" height="1920" width="1080"/></body>
</body>
</html>      

这里需要主要注意的,在页面里面访问项目静态资源,规则也是一样的,我们设置了匹配规则JCccc,所以也必须遵守这个规则。

接口还是没变:

@GetMapping("/test")
    public String test() {
        System.out.println("方法已经访问到了!");
        return "JCccc/testPage";
    }      

重启项目,访问接口,可以看到静态页面,静态资源都是访问没有问题的:

Springboot 静态资源路径配置 实例介绍

OK,这Springboot 静态资源路径配置  实例介绍 就到此吧。

还简单补充一个,

我们在电脑本地新建一个文件夹,放张图片,作为静态资源文件夹访问:

Springboot 静态资源路径配置 实例介绍
Springboot 静态资源路径配置 实例介绍

继续阅读