记忆系列–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");          //可以添加更多      }  }