spring boot系列之静态资源处理

web开发时,通常web工程都有一个webapp目录,该目录下的静态资源可以直接访问,下面简要介绍下spring boot访问静态资源的方式!
1.最笨的方式:静态资源以流方式返回给前端(最本质的处理方式)
比如maven工程的resources根目录下建立一个html的目录,然后把静态资源文件放在该目录下,并且规定任何访问路径以/static/开头的即访问该目录下的静态资源。
@Controller
public class StaticResourceController {

    @RequestMapping("/static/**") // 处理以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 = StaticResourceController.class.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();
        }
    }
}

2.Spring boot默认静态资源访问方式
Spring boot默认可以直接访问四个目录(目录处于src/main/resources资源目录下)下的文件:

classpath:/META-INF/resources/
classpath:/resources
classpath:/static/
classpath:/public/
其先后顺序,正是静态资源的查找顺序。 也就是说, 如果出现了多个同名的静态资源, 那么以前面找到的为准。
注意:优先顺序可以通过自定义static-locations的值来调整。


3.自定义静态资源目录
除了spring boot默认的静态资源目录,也可以自定义目录,比如所有/image/**的路径都会访问images目录下的资源
① 配置类方式,通过继承WebMvcConfigurerAdapter,重写addResourceHandlers方法,该方法专门用于处理静态资源。
@Configuration
public class ImageMvcConfig extends WebMvcConfigurerAdapter {
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/image/**").addResourceLocations("classpath:/images/");
      }
}
②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等默认目录下的资源。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值