Spring MVC Interview Questions and Answers Explained

Spring MVC Interview Questions and answers. These have been written to help beginners as well as experienced developers to prepare for their next interview.

3 tier architecture with mvc part of it

These Spring MVC interview questions explain request dispatch, controllers, views, validation and exception handling. Practice tracing one request through the framework, then explain how a JSON response differs from rendering a view. Each answer keeps its example beside the behavior it explains.

1. What is Spring MVC?

Spring MVC is Spring Framework’s servlet-based web framework. A DispatcherServlet receives a mapped HTTP request, finds a handler, and coordinates the response. A controller can render a view or write a response body through a message converter.

HTTP request -> DispatcherServlet -> controller -> view or response body

The controller should handle HTTP concerns and delegate business work to a service. The framework supplies request mapping, data binding, validation, exception handling and view resolution around that handler.

2. How do DispatcherServlet and ContextLoaderListener differ?

DispatcherServlet is the front controller for a Spring MVC servlet. It owns a web application context for controller-related components and dispatches requests. ContextLoaderListener can create a root application context shared by servlet contexts in a traditional WAR application. A Boot application commonly registers its context and servlet without a web.xml file.

Servlet container
  -> optional root context (ContextLoaderListener)
  -> DispatcherServlet and its web context
  -> HandlerMapping -> HandlerAdapter -> controller

Use a root context only when the application structure needs it. A servlet-specific context can see beans from its parent root context; the parent does not depend on controllers in the child context.

3. What is the front controller in Spring MVC?

The DispatcherServlet is Spring MVC’s front controller. It receives requests mapped to that servlet and delegates to the appropriate handler through framework components. It does not mean that every request to the entire server must pass through one servlet mapping.

request -> DispatcherServlet -> HandlerMapping -> HandlerAdapter
                                              -> controller method

The mapping selects the handler; the adapter invokes it. A result can be a view, a response body or another supported return type.

4. How do you configure Spring MVC without Spring Boot?

In a traditional servlet deployment, an AbstractAnnotationConfigDispatcherServletInitializer registers the DispatcherServlet and supplies configuration classes. A separate WebMvcConfigurer can customize MVC components. These are different responsibilities.

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() { return null; }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() { return new String[] { "/" }; }
}

@Configuration
@EnableWebMvc
@ComponentScan("example.web")
class WebConfig implements WebMvcConfigurer {}

A Boot application normally provides this registration automatically. Adding @EnableWebMvc to Boot gives the application fuller control over MVC configuration, so use it when that is the intent.

5. How does a controller return JSON?

A @RestController writes a handler’s return value to the response body. With a JSON message converter available and suitable content negotiation, an object can be serialized as JSON.

@RestController
class EmployeeController {
    @GetMapping("/employees/{id}")
    Employee employee(@PathVariable long id) {
        return new Employee(id, "Ada");
    }
}

record Employee(long id, String name) {}

For /employees/7, the JSON converter returns:

{"id":7,"name":"Ada"}

The converter determines the wire representation. A plain @Controller can do the same for one method with @ResponseBody.

6. Can an MVC application use several configuration classes?

Yes. Java configuration can import classes or component-scan a package. Traditional XML configuration can import other XML files. The application context still has to know where to find each configuration source.

@Configuration
@Import({PersistenceConfig.class, ServiceConfig.class})
class WebConfig implements WebMvcConfigurer {}

The imported classes contribute beans to this context. In a parent-child setup, decide whether a bean belongs in the shared root context or the servlet’s web context.

7. How do annotation-config and component-scan differ?

In XML configuration, <context:annotation-config> registers processors for annotations on beans already present in the context. <context:component-scan> additionally discovers annotated components in the named packages and registers them as beans.

<context:annotation-config />
<context:component-scan base-package="example.web" />

The second line finds components in example.web; the first line alone does not. In Java configuration, @ComponentScan supplies package scanning without these XML elements.

8. How do @Component, @Controller, @Repository and @Service differ?

All four can mark a class for component scanning. The specialized names express the class’s role: MVC handler, persistence adapter or service. @Repository also participates in persistence-exception translation when that infrastructure is configured.

@Component  -> general managed component
@Controller -> MVC handler
@Service    -> service-layer component
@Repository -> persistence component and exception-translation candidate

Choose the role annotation that matches the class. The annotation does not itself create an HTTP mapping; controller methods still need request mappings.

9. How does a ViewResolver select a view?

ViewResolver is an interface to be implemented by objects that can resolve views by name. There are plenty of ways using which you can resolve view names.

These ways are supported by various in-built implementations of this interface. The most commonly used implementation is InternalResourceViewResolver class. It defines prefix and suffix properties to resolve the view component.

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

So with the above view resolver configuration, if the controller method return “login” string, then the “/WEB-INF/views/login.jsp” file will be searched and rendered.

10. What does a MultipartResolver do?

A MultipartResolver parses a multipart HTTP request so a controller can receive parts such as an uploaded file. In a current servlet application, StandardServletMultipartResolver uses the Servlet multipart support; the servlet registration also needs multipart configuration.

multipart request -> DispatcherServlet -> MultipartResolver
                                  -> MultipartFile argument in handler

Parsing is only the first step. The application still checks file size, type, content and storage destination. A file name supplied by the client is not a safe storage path.

11. How does a controller receive an uploaded file?

Use a multipart request and bind the uploaded part to a MultipartFile argument. The handler can inspect it and pass it to a storage service after validation.

@PostMapping(path = "/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<Void> upload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) return ResponseEntity.badRequest().build();
    storage.store(file);
    return ResponseEntity.accepted().build();
}

storage represents an application service, not a framework feature. It must limit size and content, choose its own storage name and handle failures. A successful multipart parse does not make the uploaded bytes trustworthy.

12. How does Spring MVC validate request data?

MVC can invoke a Bean Validation provider for an argument annotated with @Valid or @Validated. It can also use a custom Spring Validator. The validation result must be handled by the controller or exception handling layer.

record CreateEmployee(@NotBlank String name) {}

@PostMapping("/employees")
ResponseEntity<Void> create(@Valid @RequestBody CreateEmployee request) {
    service.create(request.name());
    return ResponseEntity.accepted().build();
}

With a Bean Validation provider configured, an empty name fails validation before the method body runs. Customize the error response so API clients receive a useful field-level message without exposing internal details.

13. How can a form controller handle validation errors?

Put BindingResult immediately after the validated model attribute. The controller can then return the form view with errors, or continue when the submitted data is valid.

@PostMapping("/employees")
String create(@Valid @ModelAttribute EmployeeForm form,
              BindingResult errors) {
    if (errors.hasErrors()) return "employee-form";
    service.create(form);
    return "redirect:/employees";
}

The binding result belongs to the preceding form argument. Without it, a validation failure normally follows the framework’s exception path. A custom Validator is useful when an annotation cannot express the rule.

14. What does a Spring MVC interceptor do?

A HandlerInterceptor runs around a mapped MVC handler. Its preHandle callback can act before the controller, and afterCompletion can clean up after request processing. A servlet Filter runs earlier in the container chain and is not limited to MVC handlers.

class TraceInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) {
        request.setAttribute("startNanos", System.nanoTime());
        return true;
    }
}

Register the interceptor with WebMvcConfigurer.addInterceptors. Use Spring Security’s filter chain for authentication and authorization rather than relying on an MVC interceptor for those decisions.

15. How does Spring MVC handle controller exceptions?

A controller can handle a specific exception with @ExceptionHandler. @RestControllerAdvice applies handlers across REST controllers. MVC’s exception resolvers turn an exception into a response or view; they do not catch failures outside the MVC request path.

@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(OrderNotFoundException.class)
    ResponseEntity<String> notFound(OrderNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Order not found");
    }
}

The handler returns a 404 response for this application exception. Keep the public message safe and useful; log detailed diagnostics separately.

16. How does Spring MVC choose a locale and translated message?

A LocaleResolver determines the request locale. A MessageSource looks up translated text for that locale. A locale change mechanism can let the user select a language, but the resolver alone does not translate application strings.

request locale -> LocaleResolver -> MessageSource
                                 -> messages_fr.properties, for example

Keep message keys stable across language files and define a fallback when a translation is missing. The Spring locale reference explains resolver options.

17. How can a Spring bean access servlet context information?

A web component can receive the ServletContext through Spring injection or implement ServletContextAware. A component that specifically needs its servlet’s ServletConfig can implement ServletConfigAware. Keep most business services independent of servlet details.

@Component
class ServletInfo implements ServletContextAware {
    private ServletContext context;

    @Override
    public void setServletContext(ServletContext context) {
        this.context = context;
    }
}

The context reference represents the web application. It should not be used as a general data store for request-specific state.

18. How can an application use a container-managed JNDI data source?

An external servlet container can publish a DataSource under a JNDI name. A Spring configuration can look it up and inject it into a repository. This is a deployment choice, not a requirement of Spring MVC itself.

@Bean
DataSource dataSource() throws NamingException {
    return (DataSource) new JndiTemplate()
            .lookup("java:comp/env/jdbc/ShopDB");
}

The container must define that exact name and supply the database credentials. Verify the lookup in the target deployment; a local application without the resource will fail to start or to access data.

19. How does Spring MVC relate to a three-tier application?

MVC organizes the web presentation layer. A three-tier design separates presentation, application behavior and data access. They can coexist: a controller receives HTTP input, a service applies business rules, and a repository accesses storage.

HTTP client -> MVC controller -> service -> repository -> database
               presentation     behavior  data access

An MVC model carries data to a view or response. It is not the entire domain or persistence layer by itself. This separation helps test business rules without starting a servlet request.

20. How do you investigate a 404 from an MVC endpoint?

First check the full path that reached the server, including any context path and servlet mapping. Then inspect whether a controller method matches the HTTP method, path, headers and media type. A 404 can arise before the controller runs; changing the service method cannot fix a missing route.

request URL -> context path -> servlet mapping -> handler mapping
                                           | no match -> 404
                                           | match    -> controller

Use the application’s mapping report or framework debug logs in a development environment to see registered routes. If the method is mapped but returns a view name, also check the view resolver and template; that is a different failure path.

Happy Learning!

Leave a Comment

  1. Recently I was asked Role of handler mapper, how url is mapped to particular controller in their method

  2. Hi Lokesh,

    Recently, I was asked if we have an interface and it has two implementation classes in Spring MVC project, then what will happen or rather which class will load first when we start the server ? Given , @Qualifier is not mapped to any of the implementation classes.

    • I have gone through Spring docs but couldn’t found any defined sequence for component scanning. I hope somebody else visiting this page may answer. Thanks for asking it here.

    • Exception in thread “main” org.springframework.beans.factory.UnsatisfiedDependencyException:

  3. Recently I was asked this question. What happens when you mention the view name as empty or NULL in your controller ? How will it behave ?

  4. Where we define the name of FrontEndController.java class in web.xml as as dispatcherServlet? Means how Tomcat knows this FrontEndController.java class is servlet class .

  5. Hi Lokesh,

    I was recently asked in an Interview that If you have 1000 fields on the JSP page then how you will get all the fields in spring controller without using @ModelAttribute(“”).

  6. Hello Lokesh,

    Its very good list, i’ve following few.

    1. What if more than one Controller and its method have same URL Request mapping method, How DispatcherServlet take call?
    2. What is the difference between postHandle() and afterCompletion()?
    3. Can we say Interceptors are Spring MVC filters? If not what is the difference?

  7. Hi,
    I was recently asked in an Interview that how you will call one controller method from another controller method in spring MVC, and how you will declare a controller method from which all the request will pass through and contact other controller method for further request processing?

    • I find no reason for calling a controller’s method from another controller (except it’s URL redirect). Controllers are not meant to have any business logic, they should only receive the HTTP request, validate it and pass it to manager for handling. In any scenario where you are required to call another controller’s method – is flawed code/design – and personally I never came across such scenario in my career.

      Even then if you are asked this question, simply declare your second controller as a dependency of your first and then call the appropriate method on it as necessary.

      And for request redirection use:
      return "redirect:/yourDestinationControllerPath";

  8. Hi Lokesh,

    I was recently asked what are the different types of view resolvers ,can you please explain them.

    Thanks
    Navin

    • Hello Navin,

      The view resolver will add the extra prefix and suffix while controller responding to from server to the client. For security reason we keep all the view(.jsp) pages inside the WEB-INF/views/ folder, and we can’t access it directly. When the controller will response to the client, it DispatcherServlet(front controller) will add the prefix as “/WEB-INF/views/” and suffix as “.jsp”. Suppose the controller responding as “viewemployee”, that means “viewemployee.jsp” file is available inside the “WEB-INF/views/” directory.
      Instead of sending as “/WEB-INF/views/viewemployee.jsp” for each request, it sends the filename only, rest of the things (prefix & suffix) are taken care by the spring framework.
      Hope it will help you, if at all not clear then put the question again with details of your requirement.

      Thanks & Regards
      SSP

  9. Good Collection and explanation . Thanks brother .

    Just a request , can u elaborate the steps we need to follow to use Other view technologies like Bootstrap with Spring MVC .

  10. Hi Lokesh, For question 2, probably you need to add the ContextLoaderListener in web.xml as below:

    org.springframework.web.context.ContextLoaderListener

  11. Hi Lokesh – May I request you to create tutorials for JPA (Entity Manager)? As I can see you’ve covered all latest technology, but I see one more important is missing.

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.