You need to enable JavaScript to run this app. 无法在本地运行Spring MVC增删改查演示项目,求助解决
优惠活动
大模型
产品
解决方案
定价
更多

无法在本地运行Spring MVC增删改查演示项目,求助解决

Spring MVC项目启动失败排查解决方案

核心问题及修复方案

  • 配置类缺少必要注解
    你当前的WebMvcConfig只加了@ComponentScan,没有加@Configuration和@EnableWebMvc注解,导致Spring无法识别这是配置类,MVC相关配置也不会生效。修复后的WebMvcConfig代码如下:
@Configuration
@EnableWebMvc
@ComponentScan("springmvc")
public class WebMvcConfig {
    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}
  • Spring版本与Java版本不兼容
    你使用的Spring 5.1.5.RELEASE版本最高仅支持Java 11,但pom中maven编译插件指定了Java 15,会出现类版本不兼容错误。有两种修复方案:
    • 方案一:升级Spring版本到5.3.x及以上,匹配Java 15
    • 方案二:将maven-compiler-plugin的release版本改为11,修改配置如下:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <release>11</release>
    </configuration>
</plugin>
  • 确认组件扫描路径匹配
    你配置的@ComponentScan("springmvc")需要保证CustomerController、Service、Dao等所有被Spring管理的类都在springmvc包或其子包下,否则Controller不会被注册,访问路径会报404。
  • 确认WebAppInitializer实现类正确
    你贴出的WebAppInitializer代码需要确保类实现了WebApplicationInitializer接口,否则Servlet容器启动时不会自动执行onStartup方法加载Spring上下文,示例完整代码如下:
public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
         AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
            appContext.register(WebMvcConfig.class);
              
            ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                    "SpringDispatcher", new DispatcherServlet(appContext));
            dispatcher.setLoadOnStartup(1);
            dispatcher.addMapping("/");
    }
}
  • 确认视图文件存在
    你Controller返回的视图名为index,需要确保项目中存在/WEB-INF/views/index.jsp文件,否则会返回视图找不到的错误。

验证步骤

完成以上修改后重新打包项目,部署到Tomcat等Servlet容器中,访问根路径如果可以正常显示index.jsp内容及你设置的message参数,即为修复成功。

内容的提问来源于stack exchange,提问作者Hòa Phạm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 23:54:03