纯Java配置Spring DispatcherServlet的Spring MVC项目运行故障求助
Let’s walk through the most common pitfalls and fixes for your setup—this is exactly the kind of issue I’ve debugged multiple times when moving from plain JAR apps to Spring MVC with pure Java config.
1. Verify Your Web Application Initializer Implementation
The core of a web.xml-free Spring MVC setup is the WebApplicationInitializer (or its convenient abstract subclass AbstractAnnotationConfigDispatcherServletInitializer). If this class is missing or misconfigured, Tomcat won’t recognize your Spring setup at all.
Make sure you have a class like this in your project (it should be in a package picked up by your build tool—no extra annotations needed, Tomcat auto-detects it):
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { // Root context config (for services, data sources, etc.) @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{RootConfig.class}; } // MVC-specific config (controllers, view resolvers, etc.) @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebMvcConfig.class}; } // Map all requests to DispatcherServlet @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
2. Check Your MVC Configuration Class
Your web config class needs to enable Spring MVC and scan for controllers. Double-check these key annotations and beans:
@Configuration @EnableWebMvc // Critical for enabling Spring MVC features @ComponentScan(basePackages = "com.yourproject.controller") // Replace with your controller package public class WebMvcConfig implements WebMvcConfigurer { // Configure view resolver (assuming you're using JSPs) @Bean public ViewResolver internalResourceViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); // Path to your JSP files resolver.setSuffix(".jsp"); return resolver; } // Optional: Enable static resource access (CSS, JS, images) @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("/static/"); } }
Don’t forget the RootConfig class if you used it in the initializer—it should be a plain @Configuration class for non-MVC beans like services or repositories.
3. Fix Tomcat Deployment in IntelliJ
Since you’re moving from a JAR to a web app, you need to make sure IntelliJ is deploying a WAR artifact (not a JAR) to Tomcat:
- Go to
File > Project Structure > Artifacts - Click the
+button, selectWeb Application: Exploded>From Modules...and pick your project module - Then go to
Run > Edit Configurations, select your Tomcat server, and add the exploded artifact to theDeploymenttab - Ensure the
Application contextis set correctly (e.g.,/for root access)
4. Validate Dependencies
Even if IntelliJ downloaded Spring JARs, confirm you have all the necessary dependencies:
- spring-webmvc: The core Spring MVC library (version 5.0.4.RELEASE as per your docs)
- javax.servlet-api: Tomcat provides this at runtime, so set its scope to
provided(if using Maven/Gradle) to avoid conflicts
Example Maven dependency snippet:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.4.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies>
5. Confirm Controller Setup
Make sure your controller classes are properly annotated and mapped:
@Controller // Must have this annotation to be detected by Spring public class HomeController { @RequestMapping("/") // Maps the root URL to this method public String homePage() { return "home"; // Matches /WEB-INF/views/home.jsp (from your view resolver) } }
If you’re testing with a REST endpoint, use @ResponseBody on the method or @RestController instead of @Controller.
6. Enable Debug Logging for Troubleshooting
If nothing else works, turn on Spring’s debug logging to see what’s happening during initialization:
- Add a
logback.xml(orlog4j.properties) file tosrc/main/resources - Set the log level for
org.springframeworktoDEBUG
This will show you if the DispatcherServlet is initializing, if controllers are being scanned, and where requests are being routed (or why they’re not).
内容的提问来源于stack exchange,提问作者fpiechowski

