前端访问图片配置

在日常开发中,前端需要访问一个图片,后端需要做的一些配置,记录一下如何操作。

项目使用的是 SpringSecurity 安全框架。

首先需要配置静态资源的映射,使得特定的路由前缀可以访问静态资源。

需要实现 WebMvcConfigurer接口,它是 Spring MVC 提供的配置接口,允许我们自定义 MVC 配置,包括静态资源的映射。

我们重写了 WebMvcConfigurer 接口中的 addResourceHandlers 方法,用于配置静态资源的映射关系。 ResourceHandlerRegistry 对象用于注册静态资源的处理器。

实现

通过 addResourceHandler 方法,映射一个 profile 后面的任意路由,跳转到 D:upload/ 下,也就是说,将 profile替换了实际的路径。

java 复制代码
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        registry.addResourceHandler("/profile/**")
                .addResourceLocations("file:" + "/D:upload/");
    }

去除 Security 认证

静态资源是不需要认证的哈

在 Spring Security 中用于配置 Security 的认证情况,我们设置指定路径不进行认证。

java 复制代码
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.authorizeRequests(expressionInterceptUrlRegistry ->
            expressionInterceptUrlRegistry.antMatchers("/login", "/captchaImage", "/register").permitAll()
                    // 下面是追加对资源的释放,并设置get请求
                    .antMatchers(HttpMethod.GET, "/profile/**").permitAll()
                    // 其他请求需要认证
                    .anyRequest().authenticated())
            
    return httpSecurity.build();
}

这样就可以通过路径访问了。

前端通过路径访问即可

html 复制代码
<img src="http://localhost:8080/profile/avatar.jpg" alt="User Avatar">
相关推荐
源心锁2 分钟前
👋 手搓 gzip 实现的文件分块压缩上传
前端·javascript
追逐时光者25 分钟前
精选 10 款 .NET 开源免费、功能强大的 Windows 效率软件
后端·.net
追逐时光者27 分钟前
一款开源、免费的 WPF 自定义控件集
后端·.net
源心锁30 分钟前
丧心病狂!在浏览器全天候记录用户行为排障
前端·架构
GIS之路32 分钟前
GDAL 实现投影转换
前端
烛阴1 小时前
从“无”到“有”:手动实现一个 3D 渲染循环全过程
前端·webgl·three.js
S***q3771 小时前
Spring Boot管理用户数据
java·spring boot·后端
BD_Marathon1 小时前
SpringBoot——辅助功能之切换web服务器
服务器·前端·spring boot
Kagol1 小时前
JavaScript 中的 sort 排序问题
前端·javascript
毕设源码-郭学长1 小时前
【开题答辩全过程】以 基于SpringBoot框架的民俗文化交流与交易平台的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端