通过配置视图控制器(View Controllers)来简化视图的映射,而不需要编写额外的控制器方法。主要用于处理静态页面或简单的视图映射。
1. 使用 WebMvcConfigurer 配置视图控制器
通过实现 WebMvcConfigurer 接口并重写 addViewControllers 方法来配置视图控制器。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/backend/toLoginPage").setViewName("/backend/login.html");registry.addViewController("/backend").setViewName("/backend/index.html");}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {// 将 /backend/** 映射到 classpath:/backend/registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");}}
资源resources目录结构
2. 运行应用程序
当你启动 Spring Boot 应用程序后,访问 http://127.0.0.1:8080/backend
将会显示 index.html 页面,访问 http://127.0.0.1:8080/backend/toLoginPage
将会显示 login.html 页面。