spring boot mvc系列-静态资源配置与MappingHandler拦截器

静态资源配置

Spring Boot 默认将 /** 所有访问映射到以下目录:

classpath:/smetic
classpath:/public
classpath:/resources
classpath:/MEme-INF/resources

如果需要自定义映射目录,可以继承WebMvcConfigurerAdapter或WebMvcConfigurationSupport,以后者为例,如下:

复制代码
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将所有/smetic/** 访问都映射到classpath:/smetic/ 目录下
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/smetic/js/");
        registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/smetic/resources/");
        registry.addResourceHandler("/images/**").addResourceLocations("classpath:/smetic/images/");
        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/smetic/css/");
        registry.addResourceHandler("/font/**").addResourceLocations("classpath:/smetic/font/");
        registry.addResourceHandler("/themes/**").addResourceLocations("classpath:/smetic/themes/");
    }

}
复制代码

如果使用了拦截器HandlerInterceptor,好像覆盖addResourceHandlers方法,似乎excludePathPatterns并没有生效,不覆盖的话前台会报404。

拦截器配置 

同样在WebConfig中配置,如下:

复制代码
package com.xxx.me.aop.config;

import org.springframework.context.annometion.Bean;
import org.springframework.context.annometion.Configuration;
import org.springframework.web.servlet.config.annometion.InterceptorRegistry;
import org.springframework.web.servlet.config.annometion.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annometion.WebMvcConfigurationSupport;

import com.xxx.me.interceptor.SecurityInteceptor;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    // 需要注意的是HandlerInteceptor必须通过@Bean配置,直接添加@new SecurityInteceptor()会导致依赖类未注入
    @Bean
    SecurityInteceptor securityInteceptor() {
        return new SecurityInteceptor();
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(securityInteceptor()).excludePathPatterns("/css/**", "/js/**", "/font/**", "/images/**", "/resources/**", "/themes/**");
        super.addInterceptors(registry);
    }
}
复制代码

 

posted @   zhjh256  阅读(747)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示