Spring MVC纯Java配置类未调用致404错误,求技术解决方案
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, andfooter.jspare 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:
Lower order values mean higher priority, so this ensures Spring picks your URL-to-controller rule first.simpleUrlHandlerMapping.setOrder(-1);
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 behttp://localhost:7979/spring-mvc-demo/home.htminstead. You can verify this in your IDE's deployment settings or Tomcat'sserver.xmlfile.
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'sgetServletConfigClasses()correctly returnsExampleConfig.class. - Update your
@ComponentScanto usebasePackages = "com.example"(instead ofcom.example.*)—it's more explicit and avoids edge cases with package scanning.
- Make sure
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

