一. 问题背景
springboot导入thymeleaf依赖后,thymeleaf引入bootstrap静态资源失败,路径已经使用了th:href="@{/...}"
。
二. 解决方案
原理我在全局配置文件中定义了spring.mvc.servlet.path=/crud
,我用这个的目的是定义项目路径,使得访问localhost:8080/crud/
才有效。其实应该使用server.servlet.context-path=/crud
。
如果SpringBoot的版本是2.0及以上,静态资源会被拦截,可以尝试将静态资源放行,如下:
package com.atguigu.springboot.config;
import com.atguigu.springboot.component.LoginHandlerInterceptor;
import com.atguigu.springboot.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
//@EnableWebMvc
public class MyMvcConfig2 implements WebMvcConfigurer {
/**
* 所有的WebMvcConfigurer都会一起起作用
* @return
*/
@Bean //将组件加载进容器中
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/asserts/**", "/webjars/**");
}
};
}
}