You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC 6.0.2 Dispatcher Servlet失效(404错误)求助

解决Spring 6 MVC项目中configureViewResolvers未调用导致的404问题

核心问题分析

你的代码在Spring 5中能正常运行,但迁移到Spring 6后configureViewResolvers方法未被触发,主要有两个关键原因:

  1. Thymeleaf版本兼容性:Thymeleaf 3.x仅支持Spring 5,Spring 6需要搭配Thymeleaf 4.x版本。版本不兼容会导致Spring无法识别Thymeleaf的配置逻辑,进而跳过视图解析器的初始化。
  2. Spring 6配置逻辑调整:Spring 6对Web MVC的自动配置逻辑做了优化,手动重写configureViewResolvers注册Thymeleaf视图解析器的方式不再适配新版本的自动装配流程。

具体修复步骤

1. 升级Thymeleaf依赖至兼容Spring 6的版本

如果使用Maven,在pom.xml中更新Thymeleaf相关依赖:

<!-- Spring Web MVC 6.x -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>6.0.11</version>
</dependency>

<!-- Thymeleaf 4.x 适配Spring 6 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring6</artifactId>
    <version>4.0.0.RELEASE</version>
</dependency>

注意:Spring 6要求Servlet容器版本为5.0+(如Tomcat 10.x),确保你的容器版本符合要求。

2. 修改SpringConfig配置类

移除configureViewResolvers方法,直接将ThymeleafViewResolver注册为Spring Bean,让Spring自动识别并加载:

@Configuration
@ComponentScan("org.example")
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    private final ApplicationContext applicationContext;

    @Autowired
    public SpringConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    // 直接注册ThymeleafViewResolver Bean
    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8"); // 建议添加编码配置避免乱码
        return resolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }
}

3. 验证控制器配置

确保你的控制器类被@ComponentScan扫描到,且方法注解正确:

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "home"; // 对应/WEB-INF/views/home.html文件
    }
}

额外检查点

  • 确认WEB-INF/views目录下存在对应的HTML模板文件,文件名与控制器返回的视图名一致。
  • 检查项目编译后的class文件是否正确生成,确保配置类和控制器都被正确打包。

内容的提问来源于stack exchange,提问作者Ivan Gorbunov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:50:27