前端访问图片配置

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

项目使用的是 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">
相关推荐
咖啡八杯7 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
lizhongxuan8 小时前
AI Agent 上下文压缩利器 Headroom
后端
kyriewen8 小时前
别再 console.log 了:5 个 Chrome DevTools 调试技巧,用过就回不去了
前端·javascript·面试
Csvn10 小时前
SSH 远程管理与安全加固 — 运维的守门之道
后端
IT_陈寒10 小时前
Python搞不定字符串编码?这破玩意坑我两小时!
前端·人工智能·后端
DigitalOcean11 小时前
Laravel 开发者已在 DigitalOcean 上开通超过 10 万台服务器
前端·laravel
星始流年11 小时前
从 Tool 到 Skill——基于 LangChain 的服务端Skill实现
前端·langchain·agent
菜鸟谢11 小时前
Rust 智能指针完整详解
后端
李惟11 小时前
开源本地通信库,纯客户端 RPC,像聊天一样通信
前端
YAwu1111 小时前
深入解析 React 炫彩鼠标跟随标题组件:从坐标定位到动画性能
前端·react.js