前端访问图片配置

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

项目使用的是 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">
相关推荐
sniper_fandc40 分钟前
SpringBoot系列—入门
java·spring boot·后端
小小小小宇7 小时前
虚拟列表兼容老DOM操作
前端
悦悦子a啊7 小时前
Python之--基本知识
开发语言·前端·python
Piper蛋窝7 小时前
深入 Go 语言垃圾回收:从原理到内建类型 Slice、Map 的陷阱以及为何需要 strings.Builder
后端·go
安全系统学习8 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖8 小时前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖8 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水9 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
Sally璐璐9 小时前
零基础学HTML和CSS:网页设计入门
前端·css
老虎06279 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html