如何将ThymeleafViewResolver设为SpringMVC默认视图解析器
SpringMVC切换为ThymeleafViewResolver默认解析HTML模板配置指南
1. 添加Thymeleaf依赖
如果用Maven,在pom.xml里添加以下依赖(版本根据你的Spring版本调整:Spring5配Thymeleaf3.x,Spring6配Thymeleaf4.x):
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <!-- Spring6替换为thymeleaf-spring6 --> <version>3.1.2.RELEASE</version> <!-- 选择对应兼容版本 --> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.1.2.RELEASE</version> </dependency>
2. 修改WebMvcConfig配置
移除原有的InternalResourceViewResolver配置,替换为Thymeleaf相关Bean,同时设置优先级(order值越小优先级越高),确保Thymeleaf解析器优先生效:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.spring5.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; @Configuration public class WebMvcConfig implements WebMvcConfigurer { // 配置Thymeleaf模板解析器,指定HTML文件路径和格式 @Bean public ClassLoaderTemplateResolver templateResolver() { ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); resolver.setPrefix("classpath:/templates/"); // HTML文件存放根目录 resolver.setSuffix(".html"); // 模板文件后缀 resolver.setTemplateMode("HTML"); resolver.setCharacterEncoding("UTF-8"); resolver.setCacheable(false); // 开发阶段关闭缓存,修改HTML无需重启项目 return resolver; } // 配置Thymeleaf模板引擎 @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.setTemplateResolver(templateResolver()); return engine; } // 配置Thymeleaf视图解析器,设置最高优先级 @Bean public ViewResolver viewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); resolver.setCharacterEncoding("UTF-8"); resolver.setOrder(1); // 优先级设为1,确保比其他视图解析器先执行 return resolver; } }
3. 放置HTML视图文件
将你的hello.html放在src/main/resources/templates/目录下,这个路径和上面配置的prefix对应,Thymeleaf会自动在这里查找模板文件。
4. 检查Controller代码
确保TestController的接口返回的是纯视图名称,不要手动加前缀后缀:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class TestController { @GetMapping("/hello") public String hello() { return "hello"; // 对应templates/hello.html } }
注意事项
- 如果项目中还保留了
InternalResourceViewResolver,要么删除它,要么把它的order设为比Thymeleaf解析器大(比如2),避免解析冲突。 - 务必确认Spring和Thymeleaf版本兼容,比如Spring5.x不能搭配Thymeleaf4.x,会出现兼容性报错。
- 生产环境可以开启模板缓存(
resolver.setCacheable(true)),提升访问性能。
内容的提问来源于stack exchange,提问作者Saksham Gairola
相关产品推荐
相关产品推荐

