当前位置: > > > SpringBoot - 设置项目默认的首页(欢迎页)

SpringBoot - 设置项目默认的首页(欢迎页)

    Spring Boot 项目启动后,默认会去查找 index.html 文件作为首页面。当然我们可以指定其它页面作为首页面,下面通过样例进行演示。

一、使用 index.html 作为首页面

1,静态首页

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

2,动态首页

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

二、使用非 index.html 的文件作为首页面

1,静态首页

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

(2)一种方式通过自定义一个 Controller 来进行转发:
@Controller
public class HelloController {
    @RequestMapping("/")
    public String hello(){
        return "forward:login.html";
    }
}

(3)另一种方式是通过自定义一个 MVC 配置,并重写 addViewControllers 方法进行转发:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:login.html");
    }
}

2,动态首页

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

(2)一种方式通过自定义一个 Controller 来实现,在 Controller 中返回逻辑视图名即可:
@Controller
public class HelloController {
     @RequestMapping("/") 
     public String hello(){
         return "login";
     }
}

(3)另一种方式是通过自定义一个 MVC 配置,并重写 addViewControllers 方法进行映射关系配置即可。
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
    }
}
评论0