如何在Spring Boot项目中配置默认着陆页实现自动跳转
Spring Boot 根路径自动重定向到登录页的实现方法
以下几种方法都能实现访问 http://localhost:8080 时自动跳转到 /myapp/auth/login.xhtml:
方法一:使用控制器映射根路径
创建一个控制器类,捕获根路径的请求并处理重定向:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class RootRedirectController { @GetMapping("/") public String redirectToLogin() { // redirect前缀告诉Spring MVC执行重定向操作 return "redirect:/myapp/auth/login.xhtml"; } }
方法二:通过WebMvc配置类注册重定向规则
如果不想单独编写控制器,可以通过配置类直接注册视图控制器:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 注册根路径到目标登录页的重定向规则 registry.addRedirectViewController("/", "/myapp/auth/login.xhtml"); } }
方法三:静态HTML页面自动刷新跳转
在项目的 src/main/resources/static 目录下创建 index.html 文件,利用HTML的meta标签实现自动跳转:
<!DOCTYPE html> <html> <head> <!-- content="0" 表示页面加载后立即跳转 --> <meta http-equiv="refresh" content="0; url=/myapp/auth/login.xhtml"> </head> <body> 正在跳转到登录页面... </body> </html>
补充(针对JSF场景)
如果你的项目是JSF项目(使用xhtml视图),也可以通过配置 faces-config.xml 设置欢迎页面,直接渲染登录页(地址栏不会变化):
在 WEB-INF/faces-config.xml 中添加:
<application> <welcome-file-list> <welcome-file>/myapp/auth/login.xhtml</welcome-file> </welcome-file-list> </application>
内容的提问来源于stack exchange,提问作者Snow Arctic
相关产品推荐
相关产品推荐

