web開發(fā)中指定首頁是必備的功能檬洞,本文介紹springboot指定首頁的幾種方式。
相關(guān)環(huán)境:java1.8+,springboot2.1.4黎茎,gradle5.2.1,打包方式j(luò)ar当悔。
新創(chuàng)建的springboot項目傅瞻,不設(shè)置首頁,訪問localhost:8080盲憎,會返回404錯誤:
下面介紹幾種實現(xiàn)方法
- 利用默認(rèn)的靜態(tài)資源處理
在/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.利用默認(rèn)的模版引擎目錄
在/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窑眯,返回:
- 實現(xiàn)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