Spring Boot访问xhtml视图不带后缀报错,如何同时支持带/不带后缀访问
Spring Boot 带/不带.xhtml后缀访问视图解决方案
问题根因
- 带.xhtml后缀可正常访问是触发了Spring Boot默认静态资源映射规则,直接读取
src/main/webapp下的静态文件 - 不带后缀访问抛出模板解析异常,是因为配置的
spring.thymeleaf.prefix=classpath:/webapp/路径错误:src/main/webapp默认不属于classpath路径,Thymeleaf无法通过classpath定位到对应模板文件。
解决步骤
步骤1:修正Thymeleaf配置
修改application.properties中的Thymeleaf前缀配置,适配webapp目录的资源路径:
# 注释原有错误配置 # spring.thymeleaf.prefix=classpath:/webapp/ # 修正后配置,指向webapp根目录 spring.thymeleaf.prefix=/ spring.thymeleaf.suffix=.xhtml # 生产环境建议开启缓存提升性能 spring.thymeleaf.cache=true
注意:如果.xhtml文件存放在webapp下的子目录(如
webapp/pages/),需将prefix对应调整为/pages/。
步骤2:(可选)批量配置路径映射,省略单独编写Controller
如果仅需要做简单路径到视图的映射,无需编写单独的Controller方法,可新增Web配置类统一配置,同时支持后缀路径匹配:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; 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.addViewController("/login").setViewName("login"); registry.addViewController("/index").setViewName("index"); registry.addViewController("/register").setViewName("register"); } // 开启后缀匹配,保证带.xhtml后缀的路径也可走模板引擎渲染逻辑 @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseSuffixPatternMatch(true); configurer.setUseRegisteredSuffixPatternMatch(true); } }
验证
修改配置后重启项目,分别访问带后缀和不带后缀的路径,均可正常加载对应视图。
内容的提问来源于stack exchange,提问作者Tigray
相关产品推荐
相关产品推荐

