記憶系列–Spring Boot之addviewController 發布於 7 個月前 (09月06日) – 13

今天要記錄的addviewController,我覺得挺有意義的吧~

因為在項目開發過程中,時常會涉及頁面跳轉問題,而這個頁面跳轉不需要或者沒有任何業務邏輯處理的過程,只是單純的路由跳轉過程或者是點擊一個按鈕跳轉到另一個頁面。

例如下面例子:

    @RequestMapping("/hello")      public String hello(){          return "hello";      }

但是呢,你不可能每個Controller都寫這樣的程式碼去跳轉吧~這樣的話不就很多類似的程式碼咩?

所以Spring Boot(spring mvc)中的提供了:

①implements WebMvcConfigurer(官方推薦)

②extends WebMvcConfigurationSupport

ps:有一些比較早出的書籍會說是繼承WebMvcConfigurerAdapter,但是在spring 5或者spring boot 2.0之後已經給上面兩種方法取代。

@Configuration  public class MyWebMvcConfig implements WebMvcConfigurer {    //省略  }     @Configuration  public class MyWebMvcConfig extends WebMvcConfigurationSupport {    //省略  }

如果用idea ,直接快捷鍵alt+insert,出現有 Override methods(快捷鍵為:ctrl+o)/implement methods(快捷鍵為:ctrl+i)就有所有方法了~


下面方法同等第一個例子~

@Configuration  public class MyWebMvcConfig implements WebMvcConfigurer {      @Override      public void addViewControllers(ViewControllerRegistry registry) {          registry.addViewController("/hello").setViewName("/hello");          //可以添加更多      }  }