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); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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 让容器管理更轻松!