Springboot2指定首页的几种方式

web开发中指定首页是必备的功能,本文介绍springboot指定首页的几种方式。

相关环境:java1.8+,springboot2.1.4,gradle5.2.1,打包方式jar。

新创建的springboot项目,不设置首页,访问localhost:8080,会返回404错误:



下面介绍几种实现方法

  1. 利用默认的静态资源处理
    在/resources/static 新建index.html:
<html>
<head>
<meta charset="UTF-8">
<title>Insert</title>
</head>
<body>

    <h1>Hello Spring Boot!</h1>

</body>
</html>

访问localhost:8080,返回页面



2.利用默认的模版引擎目录
在/resources/templates新建index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index Templates</title>
</head>
<body>
    
    Index Templates
    
</body>
</html>

访问localhost:8080,返回:


3.利用SpringMVC的Controller

@Controller
public class IndexController {
    
    @GetMapping("/")
    public String index() {
        System.out.println("====================indexController");
        return "/index";
    }
    
}

访问localhost:8080,然而返回404页面:


使用@Controller返回页面,需要指定模版引擎,这里使用官方推荐的thymeleaf
在build.gradle添加依赖

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

在/resources/templates新增index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index Controller</title>
</head>
<body>
    
    Index Controller
    
</body>
</html>

访问localhost:8080,返回:


  1. 实现WebMvcConfigurer接口,在addViewControllers方法中以编程方式指定
@Configuration
public class IndexConfig implements WebMvcConfigurer{
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController( "/" ).setViewName( "forward:/index-config.html" );
        registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
        WebMvcConfigurer.super.addViewControllers(registry);
    }
    
}

在resources/static中新建index-config.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index Config</title>
</head>
<body>
    
    Index Config
    
</body>
</html>

访问localhost:8080,返回:


屏幕快照 2019-05-11 上午9.22.51.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。