我的SpringBoot版本是2.0,启动后发现页面奇丑无比:

看下目录结构:

SpringBoot默认扫描Static文件夹下的文件,这里把CSS,JS以及图片文件都放在了asserts文件夹下。
我的MVC配置文件:
package com.myspringbootweb.Config;
import com.myspringbootweb.Component.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* WebMvcConfigurationAdapter在SpringBoot2.0已过时
* 使用WebMvcConfigurationSupport来拓展SpringMvc的功能
* 也可以直接实现WebMvcConfigurer
* 既保留了所有的自动配置,又可以使用我们自己拓展的
*
* 如果加了@EnableWebMvc 则表明,SpringBoot对SpringMvc的自动配置失效,使用当前标注的这个注解的类的配置
*/
//@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//super.addViewControllers(registry);
//设置默认访问login页面
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login");
}
//静态文件
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//静态文件
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//webjar文件
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/");
}
}
看,我定义了一个静态资源和webjar访问路径,但是我的拦截器都把它们拦截了。不管我配置的多好,在项目中也是无效的。为什么? ——拦截器一巴掌给我呼死了。。。
解决方法:
把
"/static/**" 和"/webjars/** 这两个我定义的静态资源访问路径添加到拦截器的excludePathPatterns()里,也就是图上的注册拦截器那里:
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/static/**","/webjars/**","/user/login");
}
这就是告诉拦截器,你不要拦截我excludePathPatterns()里面的访问路径,别的你都可以去拦截。(护犊子..)
之后保存,重启项目,访问根路径,因为拦截器的拦截,默认跳转到登录页面。
让我们再看看效果:

自此,问题解决。
还要说一下,因为SpringBoot的版本原因,在自定义MVC配置文件中,
WebMvcConfigurationAdapter在SpringBoot2.0已过时。SpringBoot2.x只支持WebMvcConfigurationSupport和WebMvcConfigurer。也就是说,
你可以继承WebMvcConfigurationSupport来拓展SpringMvc的功能
也可以直接实现WebMvcConfigurer。SpringBoot会保留它本身的自动配置,又会使用我们自己拓展的配置。如图上我的addViewControllers(控制访问路径映射)方法和addResourceHandlers(静态资源文件配置)就是这么来的。
本文详细解析SpringBoot 2.0版本中MVC配置的常见问题及解决方案,包括如何正确配置静态资源、拦截器排除路径,以及如何避免拦截器误拦截静态资源,确保项目正常运行。
2518

被折叠的 条评论
为什么被折叠?



