前端访问图片配置

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

项目使用的是 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">
相关推荐
萧行之28 分钟前
Ubuntu Node.js 版本管理工具 n 完整安装与使用教程
linux·前端
devlei7 小时前
从源码泄露看AI Agent未来:深度对比Claude Code原生实现与OpenClaw开源方案
android·前端·后端
Jagger_8 小时前
周末和AI肝了两天,终于知道:为什么要把AI当做实习生
前端
weixin_456164838 小时前
vue3 子组件向父组件传参
前端·vue.js
沉鱼.448 小时前
第十二届题目
java·前端·算法
Setsuna_F_Seiei8 小时前
CocosCreator 游戏开发 - 多维度状态机架构设计与实现
前端·cocos creator·游戏开发
努力的小郑9 小时前
Canal 不难,难的是用好:从接入到治理
后端·mysql·性能优化
Bigger9 小时前
CodeWalkers:让 AI 助手化身桌面宠物,陪你敲代码的赛博伙伴!
前端·app·ai编程
Victor3569 小时前
MongoDB(87)如何使用GridFS?
后端
Victor3569 小时前
MongoDB(88)如何进行数据迁移?
后端