1. What is MVC?
MVC separates an application into Model, View and Controller so that presentation, request handling and application/data logic do not become one large class.
LoginBean carries login data.
2. Static vs Dynamic Request
Server can locate the resource and return it.
POST /validateLogin.html.
The request requires application processing before a response is generated.
3. Complete Project We Build
SpringMVCLogin/
│
├── pom.xml
│
├── src/main/java/
│ └── com/example/mvc/
│ ├── model/
│ │ └── LoginBean.java
│ ├── dao/
│ │ └── LoginDAO.java
│ ├── service/
│ │ └── LoginService.java
│ └── controller/
│ └── LoginController.java
│
└── src/main/webapp/
├── login.jsp
└── WEB-INF/
├── web.xml
├── spring-servlet.xml
└── views/
├── success.jsp
└── failure.jsp
| File | Responsibility |
|---|---|
pom.xml | Maven dependencies and WAR build. |
web.xml | Registers and maps DispatcherServlet. |
spring-servlet.xml | Spring MVC configuration. |
LoginBean.java | Model/data holder. |
LoginDAO.java | Data-access operation. |
LoginService.java | Business/service layer. |
LoginController.java | Handles the HTTP request. |
login.jsp | Login form. |
success.jsp | Success view. |
failure.jsp | Failure view. |
4. Complete Code — Every File
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-mvc-login</artifactId>
<version>1.0</version>
<!-- Traditional Servlet/Tomcat application -->
<packaging>war</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<spring.version>5.3.39</spring.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Tomcat supplies this at runtime -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>spring-mvc-login</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.4.0</version>
</plugin>
</plugins>
</build>
</project>
src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- Welcome page when the application root is opened. -->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!--
DispatcherServlet is Spring MVC's Front Controller.
It receives requests and delegates to mapped controllers.
-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- Initialize DispatcherServlet during startup. -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--
Requests ending in .html are handled by DispatcherServlet.
Example: POST /validateLogin.html
-->
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
src/main/webapp/WEB-INF/spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--
Scan our application packages for Spring components.
Spring discovers @Controller, @Service, @Repository,
and @Component classes.
-->
<context:component-scan
base-package="com.example.mvc"/>
<!--
Enables annotation-driven Spring MVC infrastructure.
-->
<mvc:annotation-driven/>
<!--
Converts a logical view name into a JSP location.
"success"
↓
/WEB-INF/views/success.jsp
-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
src/main/java/com/example/mvc/model/LoginBean.java
package com.example.mvc.model;
/**
* Model / JavaBean.
*
* It carries the login data.
* It does not decide whether login is valid.
*/
public class LoginBean {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
src/main/java/com/example/mvc/dao/LoginDAO.java
package com.example.mvc.dao;
import com.example.mvc.model.LoginBean;
import org.springframework.stereotype.Repository;
/**
* DAO = Data Access Object.
*
* In a real project this class would normally communicate
* with a database using JDBC/JPA/etc.
*/
@Repository
public class LoginDAO {
public boolean validateLogin(LoginBean loginBean) {
String userName = loginBean.getUserName();
String password = loginBean.getPassword();
// Demo credentials only.
if ("MSD".equals(userName)
&& "MSD@123".equals(password)) {
return true;
}
return false;
}
}
src/main/java/com/example/mvc/service/LoginService.java
package com.example.mvc.service;
import com.example.mvc.dao.LoginDAO;
import com.example.mvc.model.LoginBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service layer.
*
* Business rules should live here rather than inside
* the controller or DAO.
*/
@Service
public class LoginService {
private final LoginDAO loginDAO;
/**
* Constructor injection.
* Spring supplies LoginDAO.
*/
@Autowired
public LoginService(LoginDAO loginDAO) {
this.loginDAO = loginDAO;
}
public boolean validateLogin(LoginBean loginBean) {
// Delegate data access to DAO.
return loginDAO.validateLogin(loginBean);
}
}
src/main/java/com/example/mvc/controller/LoginController.java
package com.example.mvc.controller;
import com.example.mvc.model.LoginBean;
import com.example.mvc.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
* @Controller tells Spring that this is a web controller.
*/
@Controller
public class LoginController {
private final LoginService loginService;
@Autowired
public LoginController(LoginService loginService) {
this.loginService = loginService;
}
/**
* Handles:
*
* POST /validateLogin.html
*/
@RequestMapping(
value = "/validateLogin.html",
method = RequestMethod.POST
)
public ModelAndView validateLogin(
// Reads: <input name="uName">
@RequestParam("uName")
String userName,
// Reads: <input name="pwd">
@RequestParam("pwd")
String password
) {
// Create the Model object.
LoginBean loginBean = new LoginBean();
// Copy browser data into the Model.
loginBean.setUserName(userName);
loginBean.setPassword(password);
// Controller delegates business work to Service.
boolean valid = loginService.validateLogin(loginBean);
ModelAndView modelAndView = new ModelAndView();
if (valid) {
// Logical view name, NOT the physical JSP filename.
modelAndView.setViewName("success");
// Data made available to success.jsp.
modelAndView.addObject(
"message",
"Welcome " + userName
);
} else {
modelAndView.setViewName("failure");
modelAndView.addObject(
"errorMessage",
"Invalid username or password"
);
}
// DispatcherServlet receives this result.
return modelAndView;
}
}
src/main/webapp/login.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Spring MVC Login</title>
</head>
<body>
<h2>Spring MVC Login</h2>
<!--
Browser sends POST request to:
/validateLogin.html
-->
<form method="post"
action="${pageContext.request.contextPath}/validateLogin.html">
<label>Username:</label>
<!--
name="uName" MUST match:
@RequestParam("uName")
-->
<input type="text"
name="uName"
required />
<br><br>
<label>Password:</label>
<input type="password"
name="pwd"
required />
<br><br>
<input type="submit" value="Login" />
</form>
</body>
</html>
src/main/webapp/WEB-INF/views/success.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Login Successful</title>
</head>
<body>
<h2>Login Successful</h2>
<!-- Comes from ModelAndView.addObject("message", ...). -->
<h3>${message}</h3>
<a href="${pageContext.request.contextPath}/login.jsp">
Back to Login
</a>
</body>
</html>
src/main/webapp/WEB-INF/views/failure.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Login Failed</title>
</head>
<body>
<h2>Login Failed</h2>
<!-- Comes from Controller's ModelAndView. -->
<h3>${errorMessage}</h3>
<a href="${pageContext.request.contextPath}/login.jsp">
Try Again
</a>
</body>
</html>
5. Complete MVC Request Flow
Suppose the user enters MSD and MSD@123 and presses Login.
Step-by-step
- Browser submits
POST /validateLogin.html. - Tomcat receives the request.
web.xmlmaps the request to DispatcherServlet.- DispatcherServlet finds the controller method matching the URL and HTTP method.
@RequestParamreadsuNameandpwd.- Controller creates
LoginBean. - Controller calls Service.
- Service calls DAO.
- DAO returns the result.
- Controller creates ModelAndView.
- ViewResolver turns
successinto/WEB-INF/views/success.jsp. - JSP renders the response.
- Browser receives the final HTTP response.
Browser → DispatcherServlet → Controller → Service → DAO → Controller → ModelAndView → ViewResolver → JSP → Browser
6. Important Spring MVC Annotations
| Annotation | Beginner meaning | Used in |
|---|---|---|
@Controller |
Marks a class as a Spring MVC web controller. | Controller |
@Service |
Marks a service/business-layer component. | Service |
@Repository |
Marks a persistence/data-access component. | DAO |
@RequestMapping |
Maps a request URL and optionally its HTTP method. | Controller |
@RequestParam |
Reads a request parameter. | Controller method parameter |
@Autowired |
Asks Spring to provide a dependency. | Dependency injection |
7. @RequestMapping and @RequestParam
RequestMapping
@RequestMapping(
value = "/validateLogin.html",
method = RequestMethod.POST
)
This says that the method handles a POST request for
/validateLogin.html.
RequestParam
@RequestParam("uName")
String userName
The HTML parameter named uName is placed into the
Java variable userName.
<input name="username"> does not automatically match
@RequestParam("uName"). The parameter names must line up
unless you explicitly configure another binding strategy.
8. ViewResolver
A controller should normally return a logical view name instead of hard-coding the physical JSP path.
Controller returns:
"success"
↓
InternalResourceViewResolver
prefix = /WEB-INF/views/
suffix = .jsp
↓
/WEB-INF/views/success.jsp
Important ViewResolver types from the source material
- UrlBasedViewResolver: direct resolution of logical view names to URLs.
- InternalResourceViewResolver: JSP/Servlet/JSTL/Tiles resolution using prefix and suffix.
- ResourceBundleViewResolver: explicit view mappings through a properties file.
- XmlViewResolver: explicit view mappings through XML.
InternalResourceViewResolver.
9. Root / Parent and Child Context
The source material describes two web application contexts: a Root/Parent context for application-wide components and a Servlet/Child context associated with DispatcherServlet.
LoginService"] D["@Repository
LoginDAO"] CHILD["Servlet / Child WebApplicationContext"] C["@Controller
LoginController"] VR["ViewResolver"] ROOT --> S ROOT --> D CHILD --> C CHILD --> VR CHILD -. "can access parent beans" .-> ROOT
Root context responsibilities
- Application-wide services.
- Repositories / DAOs.
- Infrastructure such as security or persistence configuration.
Child / servlet context responsibilities
- Controllers.
- ViewResolvers.
- Web/MVC configuration.
10. ContextLoaderListener
In the traditional two-context configuration, the
ContextLoaderListener loads the Root/Parent
WebApplicationContext.
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
DispatcherServlet then creates the servlet/child WebApplicationContext.
11. XML Configuration vs Java Configuration
Spring can express configuration using XML or Java configuration. The important interview point is understanding what each configuration is responsible for rather than memorizing syntax only.
RootConfig.java
package com.example.mvc.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({
"com.example.mvc.service",
"com.example.mvc.dao"
})
public class RootConfig {
}
WebConfig.java
package com.example.mvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("com.example.mvc.controller")
public class WebConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
12. Custom Spring MVC Context Configuration
If the MVC configuration file does not use the traditional
spring-servlet.xml convention, explicitly provide its
location to DispatcherServlet.
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/my-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
The key idea is:
DispatcherServlet
↓
contextConfigLocation
↓
my-mvc.xml
13. Startup Flow vs Request Flow
Tomcat ↓ web.xml ↓ Context initialization ↓ DispatcherServlet ↓ Bean creation ↓ MVC infrastructure ↓ Application ready
Browser ↓ DispatcherServlet ↓ Controller ↓ Service ↓ DAO ↓ Controller ↓ ViewResolver ↓ JSP ↓ Browser
14. Interview Answers — Core Questions
1. Explain Spring MVC flow.
2. Why is DispatcherServlet called Front Controller?
3. What does @Controller do?
4. What does component scanning do?
5. Why do we need a Service layer?
6. Why use DAO?
7. What does @RequestMapping do?
8. What does @RequestParam do?
9. What is ModelAndView?
10. What does ViewResolver do?
11. What is InternalResourceViewResolver?
12. Why put JSP files under WEB-INF/views?
13. What is a root application context?
14. What is a child WebApplicationContext?
15. Can child context access parent beans?
15. Scenario-Based Interview Questions
Scenario 1 — @Controller exists but is not found
Scenario 2 — /validateLogin.html returns 404
Scenario 3 — username arrives as null/missing
Scenario 4 — Controller returns "success" but JSP is not found
Scenario 5 — Developer puts SQL directly in Controller
Scenario 6 — Service currently only calls DAO
Scenario 7 — Removed mvc:annotation-driven
Scenario 8 — Custom MVC XML filename
Scenario 9 — Parent context tries to access Controller
Scenario 10 — Why does "success" work without success.jsp in Controller?
Scenario 11 — Controller contains validation, database calls and HTML
Scenario 12 — POST request is mapped but GET request fails
Scenario 13 — JSP can be opened directly by URL
Scenario 14 — Spring does not inject LoginService into Controller
Scenario 15 — Application starts but controller mappings fail
Scenario 16 — Two contexts are configured. Where should Controller go?
Scenario 17 — DAO depends on Controller
Scenario 18 — ViewResolver prefix is wrong
Scenario 19 — Browser sends uName but code expects username
Scenario 20 — Interviewer asks what happens before the first request
16. Interview Traps
17. Final Memory Sheet
The one-line flow
Browser → DispatcherServlet → Controller → Service → DAO → Controller → ViewResolver → JSP → Browser
The configuration memory
web.xml ↓ DispatcherServlet spring-servlet.xml ↓ component-scan ↓ mvc:annotation-driven ↓ ViewResolver
The layer memory
Controller = HTTP / web concern Service = business concern DAO = data-access concern Model = data View = presentation
The context memory
Root / Parent ├─ Service └─ DAO Child / DispatcherServlet ├─ Controller └─ ViewResolver Child can access Parent.
The ViewResolver memory
"success" + prefix: /WEB-INF/views/ + suffix: .jsp = /WEB-INF/views/success.jsp
Spring MVC uses DispatcherServlet as the Front Controller. It dispatches requests to mapped controllers, which delegate business logic to services and data access to DAOs. The controller returns a logical view name or ModelAndView, and ViewResolver resolves that logical name to the actual view.
18. Source-Aligned Coverage
This guide follows the uploaded Spring MVC material's terminology and coverage around Model2/MVC, dynamic request flow, DispatcherServlet, Controller/Service/DAO, context configuration, Root/Child context hierarchy, ViewResolver, InternalResourceViewResolver and Java configuration.
Where this guide uses a concrete Login project, the implementation is used as the teaching example so the concepts can be connected into one complete application rather than learned as isolated definitions.