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

Spring MVC纯Java配置类未调用致404错误,求技术解决方案

Troubleshooting 404 Error in Your Pure Java-Based Spring MVC App

Let's walk through the most likely causes of your 404 error and fix them step by step, like we'd debug a colleague's code:

1. Check JSP File Placement First

Your InternalResourceViewResolver is set to look for JSPs at /WEB-INF/view/[viewName].jsp.

  • Make sure home.jsp, header.jsp, and footer.jsp are all placed directly inside the /WEB-INF/view/ folder. If they're sitting in the web root or another directory, Spring won't find them—this is the most common culprit for 404s in this setup.

2. Fix Handler Mapping Priority Conflict

When you use @EnableWebMvc, Spring automatically registers a RequestMappingHandlerMapping with an order value of 0. Your custom SimpleUrlHandlerMapping also uses a default order of 0, which can cause Spring to ignore your mapping entirely.

  • Add this line to your createHandlerMapping() method to give your custom mapping higher priority:
    simpleUrlHandlerMapping.setOrder(-1);
    
    Lower order values mean higher priority, so this ensures Spring picks your URL-to-controller rule first.

3. Confirm Your Project's Context Path

Double-check that your app is deployed to Tomcat with the context path /example.

  • If your app's deployed name is different (e.g., spring-mvc-demo), your URL should be http://localhost:7979/spring-mvc-demo/home.htm instead. You can verify this in your IDE's deployment settings or Tomcat's server.xml file.

4. Verify Your Beans Are Actually Initializing

Look at your Tomcat console output for the System.out.println messages you added (createHandlerMapping, homePageController, getViewName):

  • If those messages don't appear, your configuration class isn't being loaded:
    • Make sure ExampleAppInitializer's getServletConfigClasses() correctly returns ExampleConfig.class.
    • Update your @ComponentScan to use basePackages = "com.example" (instead of com.example.*)—it's more explicit and avoids edge cases with package scanning.

5. Update Outdated Configuration Code

If you're using Spring 4.3 or newer, WebMvcConfigurerAdapter is deprecated. Swap it for the WebMvcConfigurer interface (it has default methods, so you won't need to change any existing bean code):

@EnableWebMvc
@Configuration
@ComponentScan(basePackages="com.example")
public class ExampleConfig implements WebMvcConfigurer {
    // Keep all your existing bean definitions here
}

After making these adjustments, redeploy your app to Tomcat and test the URL again. Most 404 issues in this setup come down to path mismatches or mapping conflicts, so these steps should get your home page working.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:45:53