📅  最后修改于: 2023-12-03 15:42:34.181000             🧑  作者: Mango
在使用Spring Boot时,有时需要在程序启动时加载一些默认页面。这些页面可以作为程序的首页或帮助文档,方便用户使用。
本篇文章将介绍如何在Spring Boot中实现默认页面的加载,在程序启动时初始化,并以此作为默认页面。
首先,我们需要创建一个默认页面。可以在src/main/resources/static
目录下创建一个index.html
文件,作为程序的默认页面。
<!doctype html>
<html>
<head>
<title>Default Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is the default page.</p>
</body>
</html>
接下来,我们需要创建程序的启动类。在该类上加上@SpringBootApplication
注解,指定程序入口,并实现CommandLineRunner
接口。
@SpringBootApplication
public class Application implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// TODO: 加载默认页面
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在run
方法中,我们可以通过ServletContext
来加载默认页面。实现代码如下:
@Autowired
private ServletContext servletContext;
@Override
public void run(String... args) throws Exception {
// 加载默认页面
String defaultPage = IOUtils.toString(servletContext.getResourceAsStream("/index.html"));
servletContext.setAttribute("defaultPage", defaultPage);
}
最后,在Controller中实现一个方法,将默认页面返回到浏览器。
@RestController
public class DefaultPageController {
@Autowired
private ServletContext servletContext;
@RequestMapping("/")
public ResponseEntity<String> defaultPage() {
String defaultPage = (String) servletContext.getAttribute("defaultPage");
return ResponseEntity.ok(defaultPage);
}
}
启动程序后,访问http://localhost:8080/
,即可看到默认页面。
本篇文章介绍了如何在Spring Boot中实现默认页面的加载,并以此作为默认页面。通过实现CommandLineRunner
接口,在程序启动时加载默认页面,并在Controller中返回该页面,达到了默认页面展示的目的。