Spring Boot 2.3 访问静态页面

本文介绍如何在SpringBoot项目中配置静态资源访问路径,通过实现WebMvcConfigurer接口自定义资源处理器,使特定URL能直接访问到项目的静态文件。文中详细解释了addResourceHandler与addResourceLocations方法的作用及参数含义。
package com.example.travels.commons;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Liu
 * @date 2020/11/3 10:34:30
 * @description
 */
@Component
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 添加静态资源文件,外部可以直接访问地址
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
          
      registry.addResourceHandler("/abc/**").addResourceLocations("classpath:/static/");
    }
}

 

1.说明

1.1 addResourceHandler的参数是指 url地址 中的 path 的 格式

1.2 addResourceLocations的参数是指 项目中存放静态页面的目录

1.3 本项目用maven构建,其classpath 默认是 resources

综上3点,网址中的 /abc/ 等效于项目中的 classpath:/static/

 

2.参考文章

2.1.SpringBoot2.x过后static下的静态资源无法访问

https://blog.youkuaiyun.com/wenxingchen/article/details/84139845

2.2.基于Springboot2.3访问本地路径下静态资源的方法(解决报错:Not allowed to load local resource)

https://www.zhangshengrong.com/p/zAaOQ42eXd/

2.3.SpringBoot 第六篇 之 classpath 具体指哪个路径

https://blog.youkuaiyun.com/sss996/article/details/95336876

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值