springboot 版本 2.1.0
thymeleaf:版本在springboot配置文件中已经配置,不需要进行更改
第一次使用springboot 发现浏览器中找不到静态文件,不知道什么原因,路径也是对的。
结构如下
以下为login的部分代码块
<link href="/asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.1.3/css/bootstrap.css}" rel="stylesheet">
<link href="/asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
<img class="mb-4" src="/asserts/img/bootstrap-solid.svg" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
MyMvcConfig代码如下
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
System.out.println("加载了");
registry.addViewController("/").setViewName("login");
}
/* //第二种实现方法:添加WebMvcConfigurer组件
@Bean
public WebMvcConfigurer webMvcConfigurer() {
WebMvcConfigurer adapter = new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//将login.html映射到路径urlpath为:"/"上
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
}
};
return adapter;
}*/
}
访问后发现css和图片全部没有加载到,打开控制台发现全部是404
后来发现使用WebMvcConfigurer 就能解决这个问题,代码如下:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
System.out.println("加载了");
registry.addViewController("/").setViewName("login");
}
//第二种实现方法:添加WebMvcConfigurer组件
@Bean
public WebMvcConfigurer webMvcConfigurer() {
WebMvcConfigurer adapter = new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//将login.html映射到路径urlpath为:"/"上
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
}
};
return adapter;
}
}
于是楼主找了下原因,尽然发现了WebMvcConfigurationSupport会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置~~_~~
一下是这几种的区别:
implements WebMvcConfigurer : 不会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
@EnableWebMvc + implements WebMvcConfigurer : 会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends WebMvcConfigurationSupport :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends DelegatingWebMvcConfiguration :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
如果用WebMvcConfigurationSupport,网上说要重写addResourceHandlers方法,但是试了下没用,具体可实现的解决方案,博主还没有想到。等懂了在补充。
更改后,问题解决。
以下是问题的解决方案,需要重写addResourceHandlers:
@Configuration
public class MyMVCConfig1 extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("registry 加载了");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
System.out.println("加载了");
registry.addViewController("/").setViewName("login");
}
}