Blog

Top 10 Interview Questions for Spring MVC

Chris Jones
by Chris Jones Senior IT operations
10 April 2026

Top 10 Interview Questions for Spring MVC

A hiring manager has 30 minutes, a resume full of Spring buzzwords, and one job opening that cannot afford a weak hire. A candidate has the same 30 minutes to prove they understand more than annotations and starter-project patterns. This context defines Spring MVC interviews. Strong interviews usually turn on practical judgment. Can the candidate […]

Start hiring

A hiring manager has 30 minutes, a resume full of Spring buzzwords, and one job opening that cannot afford a weak hire. A candidate has the same 30 minutes to prove they understand more than annotations and starter-project patterns. This context defines Spring MVC interviews.

Strong interviews usually turn on practical judgment. Can the candidate explain how a request is handled from entry point to response. Can they spot where controller logic is doing too much. Can they choose between server-rendered MVC and JSON-first endpoints without hand-waving. Those are the answers that predict performance on a team.

Spring MVC has been around long enough that many developers know the terminology. Fewer can explain the trade-offs clearly under pressure or talk through the failure cases that show up in production, such as broken validation flows, ambiguous mappings, serialization issues, and exception handling that leaks implementation details. Teams also need candidates who understand where Spring MVC sits in the web stack, including the difference between a Java servlet container and a fronting web server. If that distinction is fuzzy, this comparison of Apache HTTP Server vs Apache Tomcat is a useful refresher.

This guide is built to work on both sides of the interview table. It does not stop at a list of interview questions for spring mvc. Each topic includes a stronger answer framework, common mistakes, likely follow-up questions, and visual support that helps candidates prepare and helps interviewers evaluate depth instead of confidence alone.

Use it to tighten explanations, test real understanding, and run interviews that reveal how someone will build and maintain Spring MVC applications.

1. Explain the MVC Architecture and Spring MVC Request Flow

You are in an interview, and the candidate says, "The request hits the controller, and the controller returns the response." That answer misses the part hiring managers most value. Spring MVC is useful because it separates routing, execution, view rendering, serialization, and error handling into a predictable pipeline.

The model answer should start with DispatcherServlet, because that is the entry point for Spring MVC request handling inside the servlet container. A strong candidate can explain the full path without drifting into annotation trivia.

The model answer

A clear answer sounds like this:

A client sends an HTTP request to the application. DispatcherServlet receives it and asks a HandlerMapping to find the matching controller method. Once Spring identifies the handler, a HandlerAdapter invokes that method. The controller runs business logic through services, prepares data for the response, and returns either a logical view name or an object to be written to the response body. If the method returns a view name, Spring uses a ViewResolver to locate the template. If it returns data, Spring uses HttpMessageConverter implementations to serialize it, usually as JSON.

That explanation shows real understanding because it covers both common outcomes. Server-rendered MVC and API-style responses share the same front controller, but they differ near the end of the pipeline.

A practical example helps. In an e-commerce application, GET /products/42 may map to a controller that calls a service, loads the product, adds it to the model, and returns product-details. Thymeleaf or JSP renders the HTML. In a JSON endpoint for the same product, the controller may return ProductDto instead, and Spring writes the serialized object directly to the response body.

Candidates who understand production systems often add one more detail. Interceptors, data binding, validation, and exception resolvers can all affect the request before or after the controller method runs. That is usually where debugging gets interesting.

What interviewers should listen for

Strong candidates usually describe the flow in order and assign the right responsibility to each part:

  • DispatcherServlet accepts the request and coordinates the process.
  • HandlerMapping finds the correct handler method.
  • HandlerAdapter invokes the handler.
  • The controller handles web concerns, not core business rules.
  • Services do the business work.
  • ViewResolver applies when the response is a rendered page.
  • HttpMessageConverter applies when the response body is serialized data.
  • Exception handling can reroute the flow before the final response is sent.

That last point matters. Plenty of candidates can recite the happy path. Fewer can explain what happens when binding fails, no handler matches, or a controller throws an exception.

Common mistakes

One mistake shows up constantly. Candidates collapse the whole flow into "Spring calls the controller."

That skips the framework pieces that make Spring MVC predictable and extensible.

Other weak answers usually have one of these problems:

  • They confuse the model with the response body.
  • They put business logic inside the controller when explaining the example.
  • They skip view resolution completely.
  • They cannot explain the difference between returning a view name and returning JSON.
  • They ignore where validation and exception handling fit into the lifecycle.

Follow-up questions that reveal depth

If you are interviewing, ask follow-ups that force the candidate to move beyond the textbook version:

"What changes in the request flow when the controller returns JSON instead of a view name?"

A good answer should mention @ResponseBody behavior or @RestController, plus HTTP message conversion.

"Where would you put authentication checks or request logging in this flow?"

A practical answer usually mentions servlet filters, Spring MVC interceptors, or Spring Security, depending on the concern.

"What happens if no mapping matches the request?"

The candidate should be able to talk about 404 handling and how Spring responds when no handler is found.

"What part of this flow belongs to Tomcat, and what part belongs to Spring MVC?"

That question exposes whether they understand the boundary between the servlet container and the framework. For a quick refresher on that deployment boundary, this breakdown of Apache HTTP Server and Apache Tomcat responsibilities is useful.

A practical evaluation standard

For junior candidates, a correct high-level flow is usually enough.

For mid-level and senior candidates, expect more. They should explain why the controller should stay thin, where serialization happens, how exception handling changes the response path, and what parts of the lifecycle they would inspect first when a route works locally but fails in production.

If they can sketch the flow on a whiteboard and explain where they would debug a bad response, a missing template, or a JSON conversion error, they understand Spring MVC as a working system, not just a set of annotations.

2. What is the Difference Between @Controller and @RestController

A candidate who answers this well usually understands how the application is meant to behave at the HTTP boundary. That matters in interviews because the annotation choice affects rendering, serialization, testing, and failure modes.

A diagram comparing the difference between a standard Spring MVC Controller and a RestController response output.

Model answer

@Controller is for MVC handlers that usually return a view name. Spring passes that value to a ViewResolver, which renders HTML through Thymeleaf, JSP, or another template engine.

@RestController is for handlers that write the return value straight to the response body. In practice, it is shorthand for @Controller plus @ResponseBody.

Examples make the distinction clear:

@Controller
public class AdminController {
    @GetMapping("/admin")
    public String dashboard(Model model) {
        model.addAttribute("userCount", 120);
        return "dashboard";
    }
}
@RestController
@RequestMapping("/api/products")
public class ProductController {
    @GetMapping("/{id}")
    public ProductDto getProduct(@PathVariable Long id) {
        return productService.findById(id);
    }
}

The first method prepares data for a server-rendered page. The second returns data for an API client, and Spring uses an HttpMessageConverter such as Jackson to serialize the ProductDto to JSON.

What a strong candidate adds

A good answer goes beyond "views versus JSON." It explains what Spring does with the return value.

If a @Controller method returns a String, Spring usually treats it as a view name. If a @Controller method returns an object and there is no @ResponseBody, Spring will still try to interpret the result through MVC conventions, which often leads to confusion or an error. With @RestController, the default assumption is different. The returned object is response content.

That distinction becomes important in mixed applications. Plenty of teams still serve an admin UI, internal tools, and public APIs from the same codebase. In that setup, @Controller and @RestController often belong side by side. Using one everywhere usually makes the design less clear, not more modern.

Common pitfalls

I watch for these mistakes during interviews because they show up in production code too:

  • Returning JPA entities directly from @RestController instead of DTOs, which can expose internal fields or trigger lazy loading issues
  • Adding @RestController to a class that should render templates, then wondering why the browser receives plain text instead of HTML
  • Forgetting @ResponseBody on a single API method inside a regular @Controller
  • Treating the annotation choice as stylistic rather than tied to response handling

Candidates who can explain those trade-offs usually have shipped real applications, not just tutorial projects.

Interviewer follow-up questions

Use follow-ups that test practical understanding:

  • When would you prefer @Controller in an application that also exposes REST endpoints?
  • What happens if a method in @Controller returns a POJO without @ResponseBody?
  • How do HttpMessageConverters affect a @RestController response?
  • Why can returning entities directly from an API become a maintenance problem?

A solid senior-level answer should connect annotation choice to response shape, serialization boundaries, and API stability. For candidates reviewing adjacent Java web topics, these Java interview questions and answers are a useful companion because this discussion often overlaps with servlets, JSON mapping, and object design.

3. How Does Dependency Injection Work in Spring MVC

A candidate who understands dependency injection usually understands how Spring MVC code holds up under change. I use this question to separate memorized annotation knowledge from design judgment.

A diagram illustrating an IoC container providing dependencies to Controller, Service, and Repository components via constructor injection.

Model answer

Dependency injection in Spring MVC means the Spring container creates application beans and supplies their dependencies instead of having classes construct collaborators themselves. In a typical web application, a controller depends on a service, and the service depends on a repository or client. Spring detects those beans, resolves the dependency graph, and injects the right objects at startup or at request time depending on scope.

Constructor injection is the default choice for required dependencies because it makes the contract explicit and keeps the class easy to test:

@Controller
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public String profile(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.findById(id));
        return "user-profile";
    }
}

That code tells you immediately what the controller needs. It also fits cleanly with unit tests because the dependency can be passed in directly.

What strong candidates add

Good candidates go beyond @Autowired and explain trade-offs.

Field injection still appears in older Spring MVC codebases, but it hides dependencies and makes plain unit testing harder. Setter injection works for optional collaborators or framework-driven configuration, though I rarely want it for core business dependencies. Constructor injection gives the best signal during code review because a class with six constructor arguments usually needs refactoring.

Bean scope matters too. Singleton is the default, which works well for stateless services and controllers. Request or session scope changes lifecycle and can affect thread safety, proxy behavior, and memory use. If someone injects a request-scoped bean into a singleton and cannot explain how Spring proxies that dependency, that is a warning sign.

Common pitfalls

These are the mistakes I expect mid-level and senior candidates to catch:

  • Instantiating services with new inside a controller, which bypasses the container and breaks testing, transactions, and cross-cutting behavior
  • Using field injection everywhere because tutorials do it, then struggling to write clean tests
  • Treating all beans as if they were singleton-safe without considering mutable state
  • Forgetting what happens when multiple implementations of the same interface exist
  • Explaining DI as only an annotation feature instead of a container-managed wiring mechanism

A practical follow-up is: you have two PaymentGateway implementations. How do you inject the right one? A solid answer mentions @Qualifier, @Primary, profiles, or selecting an implementation behind a strategy interface.

What interviewers should listen for

The best answers connect dependency injection to maintainability, not just syntax. Controllers stay thin because orchestration belongs in services. Services stay testable because collaborators are injected. Boundaries stay cleaner because object creation is centralized.

This is also where API design choices start to influence wiring choices. Teams building controllers around stable service contracts usually produce cleaner endpoints and simpler tests. For candidates or hiring managers who want to connect controller design with service boundaries, this guide to RESTful API design principles is a useful companion.

Interviewer follow-up questions

Use follow-ups that expose experience:

  • Why is constructor injection usually preferred in Spring MVC applications?
  • What problems does field injection create in tests and maintenance?
  • How do @Qualifier and @Primary differ?
  • When would you use request scope instead of singleton scope?
  • What happens if a bean dependency cannot be resolved at startup?

A senior-level answer should explain how the container wires objects, why constructor injection is the default choice, and where bean scope or multiple implementations create production issues.

4. Explain Request Mapping and HTTP Method Handling (@RequestMapping, @GetMapping, etc.)

A candidate says they know Spring MVC, then struggles to explain why GET /products/42 and GET /products?category=books should be handled differently. That gap shows up later in production as messy routes, ambiguous mappings, and controllers that are hard to extend.

A diagram illustrating the Spring MVC request flow, showing the DispatcherServlet, HandlerMapping, and various controllers.

The answer that reflects real project work

Request mapping is how Spring MVC matches an incoming HTTP request to a controller method. @RequestMapping is the general annotation. @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping are the focused versions teams usually prefer because they make intent obvious in the code review.

@RestController
@RequestMapping("/products")
public class ProductController {

    @GetMapping
    public List<ProductDto> list(@RequestParam(required = false) String category) { ... }

    @GetMapping("/{id}")
    public ProductDto get(@PathVariable Long id) { ... }

    @PostMapping
    public ProductDto create(@RequestBody CreateProductRequest request) { ... }

    @PutMapping("/{id}")
    public ProductDto update(@PathVariable Long id, @RequestBody UpdateProductRequest request) { ... }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) { ... }
}

That controller shows the patterns interviewers want to hear explained clearly. A collection endpoint uses GET /products. A single resource uses GET /products/{id}. Filtering belongs in query parameters. State changes use the HTTP verb that matches the operation.

Senior candidates usually go one step further and explain why these choices matter. Clear mappings reduce surprises for frontend teams, make logs easier to read, and keep API behavior aligned with common HTTP expectations. That is framework knowledge tied to maintainability, which is what hiring managers are testing.

What a strong answer should cover

A solid answer distinguishes the mapping dimensions Spring uses:

  • Path matches the URI pattern, such as /products/{id}
  • HTTP method narrows the handler to GET, POST, PUT, PATCH, or DELETE
  • Params can select a method only when certain query parameters are present
  • Headers can route based on request headers
  • Consumes restricts the expected request content type
  • Produces defines the response media type

For example, two methods can share the same path and still be valid if one handles JSON and another handles form data. That is useful in mixed systems, but it also creates confusion if the mapping rules are too clever. In interviews, I look for candidates who know the feature and know when not to overuse it.

Common mistakes candidates make

The first mistake is treating path variables and query parameters as interchangeable. They are not. Path variables usually identify a specific resource. Query parameters usually filter, sort, search, or tweak retrieval.

The second mistake is using @RequestMapping everywhere, even when a method-specific annotation would be clearer. Teams maintaining large controllers benefit from @GetMapping and friends because the route table is easier to scan.

The third mistake is ignoring ambiguity. If two controller methods can match the same request, Spring may fail at startup or throw an ambiguous mapping error. Candidates with hands-on experience usually mention this without prompting because they have hit it before.

Interviewer follow-up questions

Use follow-ups that test design judgment, not memorization:

  • What is the difference between @RequestMapping(method = RequestMethod.GET) and @GetMapping?
  • When would you use params, headers, consumes, or produces on a mapping?
  • What problems come from overloading the same path too heavily?
  • How do you handle API versioning in Spring MVC?
  • What happens when two controller methods match the same request?
  • When should an update use PUT, and when is PATCH the better choice?

If the conversation goes well, push into API consistency. Many weak Spring MVC implementations are really weak endpoint designs. Teams that care about route naming, resource boundaries, and HTTP semantics usually produce cleaner controllers. For that broader standard, this guide to REST API design principles for real-world endpoint design fits well alongside Spring-specific interview prep.

What interviewers should listen for

The strongest answers describe request mapping as part of API design, not just annotation syntax. Candidates should explain how Spring matches path plus method, how @PathVariable and @RequestParam serve different purposes, and how content type rules affect controller selection.

The best candidates also acknowledge trade-offs. Fine-grained mappings can make an API precise, but too many special cases create brittle controllers. Clean route design wins over annotation tricks every time.

5. What are Request and Response Objects How Do You Access Request Parameters

This question gets practical fast. People who have built forms and APIs tend to answer it differently from people who learned from slides.

The answer that reflects real work

The raw servlet types are HttpServletRequest and HttpServletResponse. Spring MVC lets you use them directly, but in most controller methods the better choice is a higher-level annotation.

Use @RequestParam for query or form parameters, @PathVariable for URI segments, @RequestHeader for headers, @CookieValue for cookies, and @RequestBody for JSON or XML payloads.

Examples:

@GetMapping("/search")
public List<ProductDto> search(
        @RequestParam String category,
        @RequestParam(required = false) Integer minPrice) {
    ...
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestParam String username,
                               @RequestParam String password) {
    ...
}
@PostMapping("/products")
public ProductDto create(@RequestBody CreateProductRequest request) {
    ...
}

What not to do

A common bad habit is reaching for HttpServletRequest too early. Yes, it works. No, it usually is not the cleanest option.

If a candidate says they prefer this:

String username = request.getParameter("username");

ask why they are bypassing Spring’s binding facilities. In most cases, they should not.

The exception is when they need low-level servlet access for something specific, such as request attributes added by infrastructure, multipart edge cases, or custom wrapping.

Practical pitfalls

The candidate should also talk about:

  • missing required parameters
  • malformed body content
  • encoding and content type mismatches
  • validation before business logic

This is also a good place to ask how they would extract a bearer token from the Authorization header or bind a JSON request into a DTO. People who know only form-based MVC often stumble there.

For hiring managers, one useful follow-up is: “When do you prefer @RequestBody over @ModelAttribute?”
The right answer depends on whether the input comes from a structured request body or form-style field binding.

6. How Does Exception Handling Work in Spring MVC (@ExceptionHandler, @ControllerAdvice)

A controller works fine during a demo until a service throws ResourceNotFoundException, validation fails, or JSON parsing breaks halfway through the request. That is the moment Spring MVC error handling stops being a theory question and starts showing whether the codebase was built for production.

A strong interview answer should explain scope first. @ExceptionHandler handles exceptions for one controller, or for a small set if declared in a shared base controller. @ControllerAdvice applies exception handling across controllers and is the usual choice once an application has more than a few endpoints. It gives the team one place to standardize status codes, payload shape, and logging rules.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }
}

That example is good, but a senior candidate should go one step further and explain the trade-off. Local handlers are useful when one controller has special behavior, such as returning a view for browser users instead of JSON. Global handlers are better for consistency. In API-heavy applications, I usually expect @ControllerAdvice to be the default and controller-level handlers to be the exception.

The model answer should also cover the sequence of events. An exception raised during request processing goes through Spring MVC's exception resolution chain. If a matching @ExceptionHandler method is found, Spring uses it to build the response. If not, other resolvers may map framework exceptions such as type mismatches, missing parameters, or unsupported media types. Candidates do not need to recite every resolver class, but they should understand that Spring has an ordered mechanism, not just a random catch block.

What a good answer sounds like

A solid answer usually includes four points:

  • @ExceptionHandler is for targeted handling close to the controller
  • @ControllerAdvice centralizes handling across the application
  • exceptions should map to appropriate HTTP status codes
  • error responses should be consistent and safe for clients

If the candidate is interviewing for backend API work, expect them to mention a structured error body. That usually includes an error code, message, timestamp, request path, and sometimes a correlation ID. User-facing messages should stay readable. Internal details belong in logs, not in the response body.

Common mistakes that expose weak production experience

Several answers sound correct until you press on implementation details.

  • catching Exception everywhere and returning HTTP 500 for everything
  • exposing stack traces or raw SQL errors to clients
  • duplicating logging in controllers, services, and the global handler
  • mapping domain errors to the wrong status code
  • treating validation errors and business rule violations as the same thing

That last point matters. A malformed request body, a failed bean validation check, and a domain rule such as "order already shipped" are different failure types. Strong candidates separate them and return different statuses and messages.

Interviewer follow-up questions

Use follow-ups to test whether the candidate has handled real incidents:

  • How would you return field-level validation errors from @Valid failures?
  • Where would you handle MethodArgumentNotValidException?
  • What is the difference between @ControllerAdvice and @RestControllerAdvice?
  • How do you avoid logging the same exception three times?
  • When would you keep an @ExceptionHandler local to a controller instead of moving it global?

Good candidates usually know that @RestControllerAdvice is a convenience annotation combining @ControllerAdvice and @ResponseBody, which fits JSON APIs better. They may also mention extending ResponseEntityExceptionHandler when they want to override Spring's default handling for common MVC exceptions.

What not to miss

Exception handling is not only about returning the right status. It is also about keeping controller code clean, preserving useful diagnostics for operators, and giving clients a predictable contract during failure cases. That is what separates annotation familiarity from Spring MVC experience.

7. What is Model and ModelAndView How Do You Pass Data to Views

A candidate who has built server-rendered screens should answer this one fast. They know the controller is not only choosing a route. It is preparing data the template needs to render the page.

Model holds request data for the view. ModelAndView returns the view name and the data together in one object.

Example using Model:

@GetMapping("/profile")
public String profile(Model model) {
    model.addAttribute("user", userService.currentUser());
    return "profile";
}

Example using ModelAndView:

@GetMapping("/orders")
public ModelAndView orders() {
    ModelAndView mav = new ModelAndView("orders");
    mav.addObject("orders", orderService.findRecent());
    return mav;
}

In interviews, I look for judgment, not only definitions. For straightforward handlers, Model usually keeps the method cleaner. ModelAndView can still be a good fit in older MVC codebases, or in methods where returning the view and payload as a single object reads more clearly. Neither is more "correct." The choice is mostly about readability and team conventions.

Weak answers usually fail on scope. Model data is not shared across the application. It exists for the current request so the view layer can render HTML with that data.

A practical answer should also connect this to real rendering. A controller fetches a list of products, adds it to the model, and a Thymeleaf or JSP view loops through that collection to build the page. If the page also needs a selected category, pagination data, and a feature flag, those go into the same model. That is the handoff interviewers want to hear.

Strong candidates may mention ModelMap or Map<String, Object>. That is fine, but the key distinction is whether they understand when view rendering is happening and how data reaches it. They should also know that @ModelAttribute often works alongside the model in form screens, prepopulating fields on GET requests and exposing bound objects again after validation errors on POST requests.

What interviewers should ask next

This topic gets more useful when you press on edge cases:

  • When would you choose ModelAndView over returning a String plus Model?
  • What happens to model attributes after a redirect?
  • How do you pass temporary state such as "profile updated successfully" to the next request?
  • What is the difference between model attributes and session attributes?
  • How does @ModelAttribute behave on a method versus on a parameter?

Candidates with Spring MVC experience often bring up RedirectAttributes here. That is a strong signal. It shows they know ordinary model attributes do not survive redirects, and that flash attributes exist for one more request, which is the pattern behind post-redirect-get flows.

Common pitfalls

A few mistakes show up often:

  • treating model data as application-wide state
  • using the model for redirect data instead of flash attributes
  • returning entities directly to views instead of view-specific DTOs when the template only needs part of the object graph
  • adding too much presentation logic in the controller instead of preparing simple, renderable data

That last trade-off matters in production code. Thin controllers are good, but a view should not have to untangle a complex domain model just to print a table. Good candidates usually describe shaping data for the template without pushing business rules into the controller.

8. Explain Form Handling and Validation in Spring MVC (@ModelAttribute, @Valid)

A candidate who can answer this well has usually built create and edit flows, not just read the annotations list.

In interviews, I listen for whether they describe the full request cycle. Spring binds incoming form fields into an object with @ModelAttribute, runs Bean Validation with @Valid, stores binding and validation errors in BindingResult, and then the controller decides whether to return the form view or call the service layer. That sequence matters because it explains where bad input is stopped and how the UI gets useful error messages back.

Example:

@PostMapping("/register")
public String register(@Valid @ModelAttribute("userForm") UserForm form,
                       BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "register";
    }
    userService.register(form);
    return "redirect:/login";
}

That example is simple, but it reveals several things an interviewer can probe. BindingResult must appear immediately after the validated object parameter, or Spring will not capture validation errors the way the controller expects. Returning the same view on error is also deliberate. It gives the template access to the rejected values and field errors.

Model answer

A strong answer usually sounds like this:

  • @ModelAttribute binds request parameters to a form object
  • @Valid triggers Bean Validation on that object
  • BindingResult contains field errors, global errors, and type conversion failures
  • If errors exist, return the form view and display them
  • If validation passes, call the service layer and usually follow post-redirect-get

The strongest candidates add one more distinction. Annotation-based validation handles input shape and basic field rules. The service layer still enforces business rules such as email uniqueness, duplicate usernames, or state transitions that depend on database state.

Follow-up questions interviewers should ask

This topic gets useful once you move past the happy path:

  • What happens if BindingResult is omitted?
  • How do you validate a rule that depends on a database lookup, such as unique email?
  • How do you return field-specific errors versus object-level errors?
  • How does Spring handle failed conversion for Integer, LocalDate, or enum fields?
  • Would you bind the form directly to a JPA entity, or use a dedicated DTO?

That last question separates classroom knowledge from production experience. Many teams use form DTOs instead of entities because forms often need different validation rules, fewer fields, and tighter control over mass assignment.

Common pitfalls

A few mistakes show up often in weak answers:

  • treating @Valid as a replacement for business validation
  • forgetting that type mismatch errors can happen before custom business logic runs
  • putting BindingResult in the wrong parameter position
  • binding forms directly to complex entities with relationships the user should not control
  • returning a redirect when validation fails, which loses the error state unless extra work is done

Good candidates also mention how errors reach the view layer. In Thymeleaf, for example, field errors are commonly rendered with th:errors and checked with #fields.hasErrors(...). In JSP form tags, Spring exposes similar support through the binding status.

A weak answer says, “I validate everything in the service.”
A better answer separates concerns. Controllers reject malformed input early. Services enforce business rules and persistence-related constraints.

Practical trade-offs worth hearing

@Valid works well for standard Bean Validation annotations such as @NotNull, @Email, @Size, @Min, and @Pattern. It is not enough for every case. Multi-field checks, conditional validation, and rules backed by external systems often need a custom validator or service-level validation after binding succeeds.

This is also a good place to listen for discussion of user experience. A form flow is not only about correctness. It is about returning precise, field-level feedback, preserving submitted values, and avoiding duplicate form submissions with a redirect after success. Candidates who explain those trade-offs usually have hands-on Spring MVC experience.

9. What are Interceptors in Spring MVC How Do You Implement Them

A candidate who has built Spring MVC applications usually answers this from the request path, not from a definition.

Interceptors let you run cross-cutting logic around controller execution. In Spring MVC, that usually means code that should run before the handler method, after the handler method, and after the request finishes. The interface most interviewers expect is HandlerInterceptor, and the three lifecycle methods matter:

  • preHandle runs before the controller method executes
  • postHandle runs after the controller returns, but before the view is rendered
  • afterCompletion runs after the full request is complete, including view rendering and cleanup

That lifecycle is the point. Interceptors are for work tied to Spring MVC handler execution, such as request tracing, tenant resolution, locale switching, audit logging, and timing controller requests.

Basic implementation:

@Component
public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        return true;
    }
}

Then register it in WebMvcConfigurer:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggingInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/static/**", "/login");
    }
}

A strong interview answer does not stop at registration. It explains what happens if preHandle returns false. Spring MVC stops the handler chain, so this is a common place to block a request after checking authentication state, a required header, or tenant context. That detail separates memorized knowledge from framework fluency.

The follow-up question I usually ask is: how is an interceptor different from a filter?

The practical answer is straightforward. A filter belongs to the servlet layer and can run before the request reaches Spring MVC at all. An interceptor runs inside the Spring MVC flow, after handler mapping, so it has access to the selected handler and can participate in controller-oriented concerns. If the task involves raw request or response wrapping, CORS, compression, or logic that should apply outside Spring MVC, a filter is often the better fit. If the task depends on which controller method was matched, an interceptor is usually the right tool.

There are trade-offs here. Authentication is a good example. A simple session check can live in an interceptor, but application security at scale usually belongs in Spring Security’s filter chain, where ordering, exception handling, and security context management are already solved. Experienced candidates usually say that interceptors are useful for lightweight request policies and observability, but they avoid rebuilding a security framework inside them.

Another good sign is awareness of ordering and path scope. Multiple interceptors can interact in ways that are easy to miss. Metrics may need to wrap the full request. Tenant resolution may need to happen before authorization checks. Path exclusions also matter, because intercepting static resources, health checks, or public endpoints can add noise or break expected behavior.

A high-quality answer for this question usually includes four parts: what interceptors do, how to implement and register them, how they differ from filters, and where they become a poor design choice. That gives candidates a usable model answer and gives interviewers clear follow-up prompts to test for production experience.

10. Explain Content Negotiation and Content Type Handling in Spring MVC

A lot of controller bugs are content negotiation bugs.

What a strong answer covers

The candidate should explain both sides:

  • Content-Type tells the server what the request body format is
  • Accept tells the server what response formats the client can handle

Spring MVC uses HttpMessageConverter implementations to convert request bodies into Java objects and Java return values into response bodies.

For example:

@PostMapping(value = "/products", consumes = "application/json", produces = "application/json")
public ProductDto create(@RequestBody CreateProductRequest request) {
    ...
}

If the client sends JSON with the wrong Content-Type, binding can fail. If the client requests XML and the application is not configured for it, the response negotiation can fail.

Why this matters more than people think

Candidates often say “Spring returns JSON automatically” and leave it there. That answer hides the mechanism. Interviewers should ask what performs the conversion. A strong answer mentions message converters and common serializers such as Jackson.

This also surfaces API versioning discussion. Some teams version via URI. Others use media types in the Accept header. A senior candidate does not need to advocate one universal answer, but they should understand the trade-offs.

Good signs in a candidate answer

Listen for practical awareness:

  • browser defaults can make Accept header behavior confusing
  • mixing HTML and JSON endpoints in one application requires clear controller intent
  • content negotiation problems often show up as 406 or 415 errors
  • explicit produces and consumes declarations can make APIs easier to reason about

If a candidate has debugged these issues before, they usually explain them calmly and concretely instead of hand-waving about “serialization magic.”

Top 10 Spring MVC Interview Topics Comparison

Topic Implementation complexity Resource requirements Expected outcomes Ideal use cases Key advantages
Explain the MVC Architecture and Spring MVC Request Flow Moderate–High; requires understanding DispatcherServlet and request lifecycle Spring MVC core, DispatcherServlet, HandlerMapping, view engine (JSP/Thymeleaf), configuration Clear separation of concerns, organized request processing, easier debugging Large server-rendered apps, full-stack MVPs, complex routing systems Separation of presentation/business/data, testable components, scalable architecture
@Controller vs @RestController Low; conceptual distinction with simple annotations ViewResolver for @Controller; HttpMessageConverters (Jackson) for @RestController Correct response format (HTML views vs JSON/XML) with minimal boilerplate Server-rendered pages use @Controller, REST APIs/microservices use @RestController Semantic clarity, reduces @ResponseBody boilerplate, simplifies API development
Dependency Injection in Spring MVC Moderate; requires IoC/container and bean lifecycle knowledge IoC container, bean definitions/annotations, testing mocks, possible qualifiers Loose coupling, easier unit testing, centralized wiring Layered applications, services needing interchangeable implementations, microservices Decoupling, configurable wiring, supports testing and runtime swapping
Request Mapping and HTTP Method Handling Low–Moderate; annotation-based routing is straightforward Annotations (@RequestMapping, @GetMapping, etc.), path/param handling RESTful, readable endpoints, fine-grained HTTP verb control CRUD APIs, RESTful services, resource-based routing Semantic routing, shorthand annotations, precise method restrictions
Request and Response Objects; accessing parameters Low; common web development tasks Servlet API optional, annotation support (@RequestParam, @RequestBody, @RequestHeader, @CookieValue) Flexible extraction of headers, params, body; automatic conversion Endpoints requiring headers, form/query params, JSON bodies, cookies Annotation-driven binding, automatic type conversion, reduced boilerplate
Exception Handling (@ExceptionHandler, @ControllerAdvice) Moderate; requires exception design and handler mapping Custom exceptions, @ControllerAdvice classes, error response models Centralized, consistent error responses and HTTP statuses Production APIs needing consistent error formats and logging Centralized handling, consistent HTTP codes, easier monitoring and logging
Model and ModelAndView; passing data to views Low; straightforward data-binding to templates View templates (JSP/Thymeleaf), Model/ModelAndView usage Model data available in view scope for server-side rendering Server-rendered pages, templated UIs, form pages Simple data binding to views, compatible with multiple template engines
Form Handling and Validation (@ModelAttribute, @Valid) Moderate; involves validation framework and binding lifecycle JSR-303/JSR-380 annotations, BindingResult, message resource bundles Validated user input, field-level error reporting, secure data handling User registration, forms, any user-input-heavy pages Declarative validation, automatic binding and error capture, extensible validators
Interceptors (HandlerInterceptor) Moderate; need request lifecycle understanding and registration HandlerInterceptor implementations, WebMvcConfigurer registration Centralized cross-cutting behavior (logging, auth, metrics) before/after controller Authentication, request logging, performance monitoring, CORS handling Reusable lifecycle hooks, request/response access, centralized concerns
Content Negotiation and Content Type Handling Moderate–High; requires converter configuration and negotiation strategies HttpMessageConverters (Jackson/JAXB), ContentNegotiationManager, produces/consumes settings Single endpoints serving multiple formats (JSON, XML, HTML) based on client APIs serving web, mobile, and legacy clients requiring different formats Client flexibility, reduces endpoint duplication, supports multiple consumers

Hire Vetted Spring MVC Experts, Fast

A team needs a Spring MVC hire in two weeks because a release is slipping. On paper, five candidates look interchangeable. In the interview, the gap shows up fast. One can define @RequestMapping. Another can explain why a handler method is never reached after a conflicting mapping, how validation errors should flow back to the view, and when controller advice reduces duplication without hiding useful context.

That distinction matters more than keyword coverage. Teams do not struggle because candidates have never seen Spring MVC. They struggle because many candidates have only used the happy path. Production work exposes the harder parts: odd binding failures, inconsistent exception responses, security rules applied in the wrong layer, and controllers that become cluttered because no one set clear conventions.

That is why this article is built as more than a list of prompts. It gives you a framework you can use on both sides of the table: question intent, model answers, likely follow-ups, and the mistakes that separate memorized knowledge from working experience. Candidates can prepare against a realistic bar. Hiring managers can screen for judgment, not just recall. If a candidate needs help tightening how they explain their experience under pressure, working with an interview coach can sharpen the difference between a decent answer and a hireable one.

For companies that want to reduce sourcing time, HireDevelopers.com focuses on the first-pass filtering that usually consumes the most effort. Instead of sorting through resumes that all mention Spring Boot and REST APIs, teams get access to vetted engineers across backend, frontend, full-stack, DevOps, data, AI, and mobile roles. The hiring model is flexible. Companies can bring on full-time or part-time engineers, individual contributors or full teams, across different regions with payroll and compliance support.

For Spring MVC roles, that filtering matters because resumes rarely show whether someone can reason through request flow, choose between returning a view and returning serialized data, or structure validation and exception handling cleanly. A candidate may list DispatcherServlet, @ControllerAdvice, and @Valid and still struggle to explain how those pieces interact under load or during failure scenarios.

HireDevelopers.com positions itself around that gap. The value is not just speed. It is reducing the number of weak interviews your team has to run before finding someone who can contribute in an existing codebase. For startups, that can mean shipping an MVP without building a recruiting pipeline from scratch. For engineering managers, it cuts repetitive screening work. For larger organizations, it offers a wider pool of engineers who can join through compliant engagement options.

Use the interview standards from this guide as your baseline. If you already know what strong Spring MVC answers sound like, hire against that bar instead of settling for resume familiarity.


HireDevelopers.com helps companies hire rigorously vetted software engineers across any tech stack, time zone, and budget. Learn more at HireDevelopers.com.

... ... ... ...

Simplify your hiring process with remote ready-to-interview developers

Already have an account? Log In