Spring/SpringBoot系列之SpringBoot处理静态资源【十三】

进行web开发的时候,有很多静态资源,比如html、图片、css等。在前后端不分离的架构下,以前的传统的spring项目里面有一个webapp目录,只要把静态资源放到该目录下就可以直接访问,但是基于SpringBoot的工程没有这个目录,那应该如何处理?

1. 通过流直接返回给前端

在resources根目录下建立一个html的目录,然后创建一个测试的index.html,然后把index.html文件放在html目录下,并且规定访问路径为/index时访问静态资源index.html,实现代码:

package com.linyf.demo.springboot.staticResource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

@Controller
public class StaticResourceController {

    @RequestMapping("/static/**")
    public void getHtml(HttpServletRequest request, HttpServletResponse response) {
        String uri = request.getRequestURI();
        String[] arr = uri.split("static/");
        String resourceName = "index.html";
        if (arr.length > 1) {
            resourceName = arr[1];
        }

        String url = this.getClass().getResource("/").getPath() + "html/" + resourceName;
        try {
            FileReader reader = new FileReader(new File(url));
            BufferedReader br = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }
            response.getOutputStream().write(sb.toString().getBytes());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述
启动项目后,访问http://localhost:8088/static/(我这里指定了项目访问端口为8088),会输出index.html:
在这里插入图片描述
再访问http://localhost:8088/static/index1.html,则会输出index1.html:
在这里插入图片描述
实现过程很简单,就是先从路径中分离出来资源uri,然后从static目录下读取指定文件,缺省为index.html,输出到前端。

因为只做简单演示,所以这里只处理了文本类型的文件,图片文件可以做类似的处理。

这个办法虽然有点笨,却是最本质的东西。

2. Spring boot默认静态资源访问方式

Spring boot默认对/**的访问可以直接访问四个目录下的文件:

  1. classpath:/public/
  2. classpath:/resources/
  3. classpath:/static/
  4. classpath:/META-INFO/resouces/

在资源文件夹resources下建立如下四个目录:
在这里插入图片描述
注意蓝色条下的资源文件夹resources与类路径下的文件夹classpath:/resources是不同的,蓝色条下的resources代表的是该目录下的文件为资源文件,在打包的时候会将该目录下的文件全部打包的类路径下:
在这里插入图片描述
这个名称是可以改的,在pom.xml指定资源目录即可:
在这里插入图片描述
而类路径下的resources是spring boot默认的静态资源文件夹之一,和public、static以及MEAT-INFO/resources的功能相同。

重启应用后,依次访问:

  • http://localhost:8088/1.html
  • http://localhost:8088/2.html
  • http://localhost:8088/3.html
  • http://localhost:8088/4.html

四个url就可以访问到各自对应的静态资源了。内容可以自定义,就不贴图了。

3. 自定义静态资源目录

其实静态资源目录是可以自定义的。

下面定义一个images的目录来存放图片,所有/image/**路径都会访问images目录下的资源:
在这里插入图片描述
添加资源处理器:

package com.linyf.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ImageMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**")
                .addResourceLocations("classpath:/images/");
    }
}

WebMvcConfigurer 是Spring提供的一个配置mvc的适配器接口,里面有很多配置的方法,addResourceHandlers就是专门处理静态资源的方法。

说明:因为我这里用的springboot版本是2.2.5,所以需要实现WebMvcConfigurer ,如果是1.5.x之前的版本,需要继承WebMvcConfigurerAdapter。

测试,访问localhost:8088/image/timg.jpg:
在这里插入图片描述
其实除了上面的办法还有一种更简单的办法,就是直接在application.yml中配置即可:

spring:
  mvc:
    static-path-pattern: /image/**
  resources:
    static-locations: classpath:/images/

说明:

  • static-path-pattern:静态资源访问模式,默认为/**,多个可以逗号分隔;
  • static-locations:资源目录,多个目录逗号分隔,默认资源目录为classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

注意,这个配置会覆盖Spring boot默认的静态资源目录,如果按示例中配置,则无法再访问static、public、resources等目录下的资源了。

如果这四个目录中存在相同名称的资源,通过static-locations的默认值顺序就是访问的优先顺序,当然也可以通过自定义static-locations的值来调整优先顺序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值