首先,在默認的springMVC自動配置下,會加載靜態資源文件夾下的index.html文件作爲項目首頁。springBoot默認的靜態資源路徑有五個,分別是項目的根路徑/
,classpath:/META-INF/resources/
,classpath:/resources/
,classpath:/static/
,classpath:/public/
,優先級同顯示順序。
如圖,項目啓動後,會將static目錄下的index.html作爲項目的首頁,如果我想要將templates下的login.html作爲項目的首頁,需要怎麼做呢?
- 自定義控制器攔截相關請求
@Controller
public class LoginController {
@RequestMapping({"/","/index.html"})
public String login(){
return "login";
}
}
在上面的控制器中,攔截了/
和/index.html
請求,返回的login通過字符串(thymeleaf默認配置)拼接會指向templates目錄下的login.html
,項目重新啓動後,訪問首頁即爲login.html。
- 使用WebMvcConfigurerAdapter擴展SpringMVC的功能
@Configuration
public class MyWebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
}
@Configuration
public class MyWebMvcConfiguration extends WebMvcConfigurerAdapter {
@Bean
public WebMvcConfigurerAdapter myAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
};
return adapter;
}
}
這裏提供了兩種寫法,功能上都能實現擴展。
第一種寫法直接添加視圖映射,將兩個請求映射到templates下的login.html;第二種寫法是通過向容器中添加WebMvcConfigurerAdapter組件的方式實現,自定義的組件和springBoot默認的組件都會生效。兩種方法都需要標註@Configuration註解並繼承WebMvcConfigurerAdapter 抽象類,另外,寫法二的返回對象需要標註@Bean,添加進容器中。
- 實現WebMvcConfigurer接口進行擴展
該方法與方法2類同,原理基本一致,WebMvcConfigurerAdapter抽象類也是實現了WebMvcConfigurer接口的。
當你在用第二種方法實現sprignMVC功能擴展時可能會發現,該類已經被Deprecated棄用了。
spring5推薦使用的WebMvcConfigurer 接口使用也非常方便,重寫addViewControllers方法添加組件。使用習慣和之前沒有太大改變,但接口有接口的好處,畢竟單繼承多實現,另外,直接實現接口的方式會比繼承抽象類更加簡潔,省去了抽象類的部分實現。
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
}