(8)spring boot-默認訪問首頁

前面有說到,默認訪問首頁,有這樣的方法:

在靜態資源文件夾下,寫上一個index.html,就可以默認訪問index.html了:

即輸入localhost:8080/,就訪問這個界面。

但是,這樣不夠靈活。

可以自己配置一個配置類來部分接管webMvcConfiguration

@Configuration

public class MyConfig extends WebMvcConfigurerAdapter {

    @Override

    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/jiangyi").setViewName("success");

    }

當然,一般用這個:(還是在上面那個類裏面寫)

//所有的WebMvcConfigurerAdapter組件都會起作用

@Bean

public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){

    WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){

        @Override

        public void addViewControllers(ViewControllerRegistry registry) {

           registry.addViewController("/").setViewName("login");

           registry.addViewController("/index.html").setViewName("login");

        }

    };

return adapter;

}

idea中使用技巧:ctrl+o,可以選擇想要重寫的方法。

shift+F6,可以更改文件名。

這樣,在訪問localhost:8080/index.html或者localhost:8080/時就會訪問login.html了。

注意,這裏一定要@Bean,將組件註冊在容器中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章