初识SpringBoot——设置SpringBoot应用默认首页

tech2022-07-29  143

一、使用index.html作为欢迎页面

1、静态页面

SpringBoot 项目在启动后,首先会去静态资源路径(resources/static)下查找 index.html 作为首页文件。

2、动态页面

如果在静态资源路径(resources/static)下找不到 index.html,则会到 resources/templates 目录下找 index.html(使用 Thymeleaf 模版)作为首页文件。

二、使用其他页面作为欢迎页面

1、静态页面

假设我们在 resources/static 目录下有个 login.html 文件,想让它作为首页。

一种方式通过自定义一个 Controller 来进行转发:

@Controller public class HelloController { @RequestMapping("/") public String hello(){ return "forward:login.html"; } }

另一种方式是通过自定义一个 MVC 配置,并重写 addViewControllers 方法进行转发:

@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:login.html"); } }
2、动态页面

假设我们在 resources/templates 目录下有个 login.html 文件(使用 Thymeleaf 模版),想让它作为首页。

一种方式通过自定义一个 Controller 来实现,在 Controller 中返回逻辑视图名即可:

@Controller public class HelloController { @RequestMapping("/") public String hello(){ return "login"; } }

另一种方式是通过自定义一个 MVC 配置,并重写 addViewControllers 方法进行映射关系配置即可。

@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); } }

注意 要想能访问template下的动态页面,必须要引入thymeleaf相关的jar包:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
最新回复(0)