Understanding the Execution Process of Spring MVC with a Sample Application
This article explains how Spring MVC works by walking through a simple SSM project, showing the controller implementation, configuration files, deployment steps, and then detailing the ten-step request‑handling flow from DispatcherServlet to the final view rendering.
1. Walk through a simple Spring MVC program
In an SSM project, Spring MVC serves as the controller layer to handle incoming HTTP requests and return responses. The HelloController class implements the Controller interface and overrides handleRequest .
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView();
String msg = "HelloSpringmvc!";
mv.addObject("msg", msg);
mv.setViewName("test");
return mv;
}
}2. Create the Spring MVC configuration file ( springmvc.xml ) under the resources directory.
3. Configure the front controller DispatcherServlet in web.xml .
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
1
dispatcherServlet
/4. Create the JSP view file (e.g., test.jsp ) under /WEB-INF/jsp/ .
5. Deploy the project to Tomcat and run it. If a 404 error occurs, verify that the generated WAR contains the required WEB-INF/lib directory.
2. Understanding the Spring MVC execution flow
The request handling proceeds through the following steps:
DispatcherServlet : Acts as the front controller, receiving and intercepting all incoming requests.
HandlerMapping : Looks up the appropriate handler (controller) based on the request URL.
HandlerExecution : Executes the resolved handler.
HandlerAdapter : Invokes the controller method, passing request and response objects.
The controller (or service layer) populates a ModelAndView with data and sets the logical view name.
HandlerAdapter returns the view name to DispatcherServlet .
DispatcherServlet uses a view resolver (e.g., InternalResourceViewResolver ) to resolve the logical view name to a concrete view resource.
The resolved view (JSP) is rendered, producing the final HTML response.
The response is sent back to the client, completing the request cycle.
Below is a diagram illustrating the overall execution process:
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.