⌂ Home
Unit 23 · Spring MVC Architecture

Spring MVC — Layman Concepts

Understand what MVC really means, how a web request actually travels through Spring, what DispatcherServlet is, why ViewResolver exists, and the difference between the two application contexts — all explained with zero jargon.

MVC Pattern Explained DispatcherServlet Deep Dive Full Request Lifecycle Context Hierarchy XML vs Java Config Interview Q&A
Browser DispatcherServlet Controller Service → DAO ViewResolver JSP → Browser

What is MVC? (Model-View-Controller)

“Separating concerns so your code doesn't become a mess”

🍽 Restaurant Analogy

Customer (Browser) orders food → Waiter/Controller takes the order and coordinates → Chef/Service prepares the food using business rules → Store Room/DAO fetches the actual ingredients (data) → Plate/View is how the food is presented back to the customer.

Model

Holds the data. In Spring MVC, the Model is a Map-like container that stores data to pass from Controller to View. It also refers to your Java domain objects (LoginBean, Employee, etc.).

Example: model.addAttribute("user", userObj)

View

Presents the data to the user. In classic Spring MVC, views are JSP files. The view receives data from the Model and renders HTML. The Controller decides which view to show — it never writes HTML itself.

Example: welcome.jsp displays the user's name from the model.

Controller

The coordinator. It receives HTTP requests, calls the Service layer to process business logic, puts results into the Model, and returns the name of the View to render. It's the traffic director.

Example: @Controller LoginController

🔑 Why MVC? Without MVC, one class would handle HTTP parsing, business logic, data access, AND HTML rendering — impossible to maintain. MVC divides responsibility so teams can work in parallel and code stays clean.

DispatcherServlet — The Entry Point of Every Request

“The one servlet that controls everything”

🔖 Airport Control Tower Analogy

DispatcherServlet is like an Airport Control Tower. Every plane (HTTP request) must communicate with the control tower first. The tower knows which runway (controller method) to direct each plane to, coordinates the landing, and directs the plane to the correct gate (view). No request bypasses the control tower.

What DispatcherServlet Does

  • Acts as the single entry point for all HTTP requests
  • Receives request, delegates to HandlerMapping to find the right controller method
  • Calls the controller method
  • Receives the ModelAndView returned by the controller
  • Delegates to ViewResolver to find the actual view file
  • Renders the view and sends response back

web.xml Configuration

<servlet> <servlet-name>mvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> <!-- all requests --> </servlet-mapping>

url-pattern / means DispatcherServlet handles ALL incoming requests.

🚨 Common Confusion

DispatcherServlet is NOT the controller. It's the front controller — a design pattern where one class receives all requests and delegates them appropriately. Your @Controller classes are the actual controllers.

Complete Request Lifecycle Step-by-Step

“What happens from the moment you press Enter in the browser?”

@Controller and @RequestMapping Explained

“How a Java method becomes a web URL handler”

@Controller // This class handles HTTP requests public class LoginController { @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLoginForm(Model model) { model.addAttribute("message", "Please log in"); return "login"; // View name: /WEB-INF/views/login.jsp } @RequestMapping(value = "/login", method = RequestMethod.POST) public String processLogin(@RequestParam String username, @RequestParam String password, Model model) { boolean ok = loginService.validate(username, password); if (ok) return "welcome"; model.addAttribute("error", "Invalid credentials"); return "login"; } }

@RequestMapping

Maps a URL path + HTTP method to a Java method. Can be on the class level (base path) and method level (sub path). @GetMapping and @PostMapping are shortcut annotations for common cases.

Return values from controller

  • String — View name to render
  • ModelAndView — Combined model + view name
  • "redirect:/url" — Redirect to another URL (browser changes URL bar)
  • "forward:/url" — Internal forward (browser URL doesn't change)
🚨 redirect vs forward

redirect: Server tells browser "go to this new URL". Browser makes a SECOND request. URL in address bar changes. Good for POST-Redirect-GET pattern to prevent form resubmission on refresh.
forward: Server internally forwards the request to another URL. Browser sees the same URL. Only one request.

HandlerMapping — The URL-to-Method Router

“How Spring knows which controller method handles which URL”

📞 Telephone Directory Analogy

HandlerMapping is like a telephone directory. When DispatcherServlet gets a request for /login, it asks HandlerMapping: "Who handles /login?" HandlerMapping looks up its directory (all @RequestMapping annotations) and returns: "That's LoginController.showLoginForm() for GET requests."

RequestMappingHandlerMapping (Default)

The most common HandlerMapping. It scans all @Controller classes at startup, reads @RequestMapping, @GetMapping, @PostMapping annotations, and builds an internal map of URL patterns to controller methods. When a request arrives, it looks up the URL in this map in milliseconds.

ViewResolver — Turning View Names into Actual Files

“Why do we return just 'login' and not the full path?”

🕑 Abbreviation Expander Analogy

Returning "login" from a controller is like giving a short code. ViewResolver is the translator that expands it. It has a prefix (/WEB-INF/views/) and a suffix (.jsp), so it converts "login" into /WEB-INF/views/login.jsp.

<!-- In XML config --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> // In Java config @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver vr = new InternalResourceViewResolver(); vr.setPrefix("/WEB-INF/views/"); vr.setSuffix(".jsp"); return vr; }

Why put JSPs under /WEB-INF/? Files under /WEB-INF/ cannot be accessed directly by the browser (it gets a 404). Only the server (via ViewResolver) can access them. This forces all requests to go through the Controller first — securing your views.

🚨 Interview Trap

Why are JSPs placed in /WEB-INF/views/? Answer: So browsers cannot access JSP files directly, bypassing security and controller logic. Every view must go through the DispatcherServlet → Controller → ViewResolver chain.

Two Application Contexts — Root vs Servlet

“Why are there two Spring containers?”

🏠 Company Hierarchy Analogy

Think of a company: Root Context = Head Office (has shared company-wide resources: HR, Finance, Shared DB). Servlet (Web) Context = Branch Office (has web-specific staff: Controllers, ViewResolver). Branch can use Head Office resources, but Head Office doesn't know about branch-specific web stuff.

Root Application Context

Created by ContextLoaderListener. Contains shared beans: Services, DAOs, DataSource, JPA config, Transaction management. Any web component can access these beans.

Config file: applicationContext.xml

Beans inside: @Service, @Repository, DataSource, EntityManagerFactory, @Transactional setup

Servlet (Web) Application Context

Created by DispatcherServlet. Contains web-specific beans: Controllers, ViewResolver, HandlerMapping, HandlerAdapter. It can access Root context beans (parent-child relationship).

Config file: [servlet-name]-servlet.xml (e.g., mvc-servlet.xml)

Beans inside: @Controller, ViewResolver, interceptors

🚨 Interview Trap

Can a Service bean in Root context access a Controller bean in Servlet context? NO! Parent (Root) cannot access children (Servlet context). But a Controller in Servlet context CAN access Service beans from Root context. It's a one-way relationship: child sees parent, parent does NOT see child.

🔑 Why two contexts? Multiple DispatcherServlets can share the Root context. Each Servlet has its own isolated web context. This allows you to have different web layers (APIs, admin panel) sharing the same service/DAO layer.

XML-Based Spring MVC Setup Explained

“The classic way to configure Spring MVC”

<!-- applicationContext.xml (Root) --> <context:component-scan base-package="com.acc.service, com.acc.dao"/> <tx:annotation-driven/> <!-- mvc-servlet.xml (Web/Servlet) --> <mvc:annotation-driven/> <!-- enables @RequestMapping, @Valid, etc --> <context:component-scan base-package="com.acc.controller"/> <bean class="...InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>

What does <mvc:annotation-driven/> do? It registers RequestMappingHandlerMapping, RequestMappingHandlerAdapter, and message converters — everything needed to process @RequestMapping, @PathVariable, @RequestParam, @Valid, etc. Without this, most MVC annotations would be ignored.

Java-Based Config — No More XML

“Same setup, but in pure Java code”

@Configuration @EnableWebMvc // equivalent of <mvc:annotation-driven/> @ComponentScan("com.acc.controller") public class WebConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver vr = new InternalResourceViewResolver(); vr.setPrefix("/WEB-INF/views/"); vr.setSuffix(".jsp"); return vr; } } // Replace web.xml with Java initializer: public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class[] getRootConfigClasses() { return new Class[] {RootConfig.class}; } protected Class[] getServletConfigClasses() { return new Class[] {WebConfig.class}; } protected String[] getServletMappings() { return new String[] {"/"}; } }

Model, ModelAndView, @ModelAttribute

“How data gets from Java to the JSP page”

Model

A container (like a Map) you add data to in your controller. Spring passes it to the view automatically.

public String show(Model model) { model.addAttribute("name", "Rahul"); return "welcome"; } // In JSP: ${name} prints "Rahul"

ModelAndView

Combines model data AND view name in one object. Less common with modern annotations but appears in older code.

ModelAndView mav = new ModelAndView(); mav.setViewName("welcome"); mav.addObject("name", "Rahul"); return mav;

@ModelAttribute

Two uses: (1) On a method parameter — binds form data to a Java object automatically. (2) On a method — pre-populates model data before any controller method in the class runs.

public String save( @ModelAttribute Employee emp) { // emp is bound from form fields }

Top Interview Questions with Answers

“Spring MVC questions that always appear in interviews”

What is DispatcherServlet and what is its role?
DispatcherServlet is the front controller in Spring MVC. It is the single entry point for all HTTP requests. It delegates to HandlerMapping to find the right controller, then to HandlerAdapter to call it, and finally to ViewResolver to render the response. It coordinates the entire request-response cycle.
What is the difference between @Controller and @RestController?
@Controller is used for traditional MVC controllers that return view names (JSP pages). The return value goes through ViewResolver. @RestController = @Controller + @ResponseBody, meaning the return value is written directly to the HTTP response body (JSON/XML) — no ViewResolver involved. Used for REST APIs.
What is HandlerMapping?
HandlerMapping maps incoming HTTP requests to the appropriate controller method. The default implementation (RequestMappingHandlerMapping) scans all @Controller classes at startup, reads @RequestMapping annotations, and builds a URL-to-method lookup table used for every request.
What is InternalResourceViewResolver? What is prefix and suffix?
InternalResourceViewResolver converts logical view names (returned by controllers as strings) to actual JSP file paths. Prefix is the directory path (e.g., /WEB-INF/views/) and suffix is the file extension (e.g., .jsp). So returning "login" becomes /WEB-INF/views/login.jsp.
What is the difference between Root Application Context and Servlet Application Context?
Root context is created by ContextLoaderListener and contains shared backend beans (Services, DAOs, DataSource, transactions). Servlet context is created by DispatcherServlet and contains web beans (Controllers, ViewResolver). Servlet context inherits from Root context (can access Root beans). Root context cannot see Servlet context beans. This allows multiple DispatcherServlets to share the same backend.
What is the difference between redirect and forward?
redirect: sends 302 response to browser, browser makes a NEW request to the new URL, URL in address bar changes, original request data is lost. forward: server-side forward, browser makes only ONE request, URL in address bar doesn't change, same request/response objects are passed to the forwarded resource. Use redirect after POST (PRG pattern) to prevent duplicate form submissions.
Why should JSP files be placed under /WEB-INF/?
Files under /WEB-INF/ are not directly accessible by browsers. A browser request for a URL inside /WEB-INF/ returns a 404. This forces all access to go through the DispatcherServlet and Controller, ensuring proper security, validation, and business logic is applied before any view is rendered.

⚡ Memory Cheat Sheet

“Last-minute revision before your interview”

DispatcherServlet
Front Controller
Single entry point
HandlerMapping
URL → Controller method
RequestMappingHandlerMapping
ViewResolver
"login" →
/WEB-INF/views/login.jsp
Root Context
ContextLoaderListener
Services, DAOs, Transactions
Servlet Context
DispatcherServlet
Controllers, ViewResolver
redirect:
Browser makes 2nd request
URL changes
forward:
Server-side, 1 request
URL stays same
/WEB-INF/ JSPs
Not browser-accessible
Forces security
@ModelAttribute
Binds form fields
to Java object
↑ Back to top