Prev Next

Spring / Spring MVC Interview questions

Last updated

Last updated 19 September 2026. Default examples are mid-level Spring and Java 17–21. Junior and senior sit in labeled sections so the first screen is not a fresher dump.

Spring MVC is the servlet-stack web layer: one DispatcherServlet, handler mappings, argument resolvers, and view resolution. REST interviews still live here even when the team also has WebFlux. This hub covers the servlet stack only. WebFlux is a different concurrency model; do not mix the answers.

Junior

@Controller methods return a view name or a ModelAndView. @RestController is @Controller plus @ResponseBody, so the return value is written to the response body, usually JSON via HttpMessageConverter. @RequestParam binds query or form fields. @PathVariable binds URI template variables. @RequestBody binds the body. Mixing @RequestBody with application/x-www-form-urlencoded is a junior trap.

ModelAndView holds the view name and the model map. Spring resolves the view through ViewResolver. That is the harvest page we already titled. RedirectAttributes exist because a redirect is a new request; flash attributes survive one redirect only.

Validation: @Valid on a @RequestBody plus a BindingResult or an @ExceptionHandler for MethodArgumentNotValidException. Returning 200 with an error payload is not an API. 400 with a stable error shape is.

Content negotiation uses Accept and produces/consumes on @RequestMapping. If you ignore produces, you will ship XML to a client that sent Accept: application/json because Jackson and Jackson XML both look eligible.

Mid-level

HandlerInterceptor.preHandle can abort the chain. postHandle runs after the controller if the view will render. afterCompletion always runs for cleanup. Use a Filter when you must wrap the servlet InputStream or apply to error dispatches. Use an interceptor when you need the HandlerMethod, including mapping annotations.

Exception handling: @ControllerAdvice plus @ExceptionHandler is the default. ResponseStatusException is fine for simple cases. Do not catch Exception in every controller. For REST, return Problem Details (RFC 9457) if the API is public; pick one shape and keep it.

File upload uses MultipartFile and a multipart resolver. Size limits belong in configuration, not folklore. Streaming large uploads to disk matters on a 256m heap.

Locale and time zone: LocaleResolver and a clock you can fake in tests. Do not call LocalDate.now() inside a controller if the test must freeze the date. Inject a Clock.

Security is not MVC, but interviews glue them. CSRF applies to browser form posts, not to a JWT API that never uses cookies. If you disable CSRF on a cookie-session app, say why you accepted the risk.

Senior

Senior MVC is about HandlerAdapter customization, RequestMappingHandlerMapping order, and how functional RouterFunction endpoints coexist with annotated controllers. You should know where to put an HttpMessageConverter and why adding one in a random @Bean can reorder Boot's defaults badly unless you use a WebMvcConfigurer.

Async MVC: Callable and DeferredResult use a separate thread. The servlet thread is released. You must propagate MDC and security context. Timeout handling is not optional. This is not WebFlux; it is still the servlet container with an extra executor.

Character encoding, forwarded headers behind Cloudflare, and X-Forwarded-Proto for redirects: get these wrong and OAuth callbacks break in production only. ForwardedHeaderFilter or server.forward-headers-strategy=framework is the Boot knob.

Performance: avoid loading a 50-question answer dump into one HTML document. That is why this site now teasers child questions and links the canonical URL. MVC pages that serialize the entire domain model as JSON have the same smell.

Probe yourself

@RequestParam versus @PathVariable?

Query or form field versus a URI template variable. /users/42 uses a path variable; /users?id=42 uses a request param.

When is a Filter the wrong tool compared with a HandlerInterceptor?

When you need the matched HandlerMethod or you only want to run for MVC handlers, not for every servlet request.

Why do flash attributes exist?

A redirect starts a new request. Flash attributes store data for that one follow-up request only.

Related questions on this topic are linked below. Read the full answer on the question URL; this hub does not repeat those answers.

Pitfalls interviewers still use

Returning Map<String,Object> from every controller is not an API. It has no schema, no compatibility story, and no type. Use a DTO or a record. Version with a header or a URL prefix if you cannot break clients.

@ExceptionHandler on the controller only covers that controller. A forgotten advice class is why one endpoint returns JSON errors and another returns a Tomcat HTML page. Put the advice in a scanned package and test it with MockMvc.

Consuming application/json and sending a form post from a browser test is a 415. That is not a Spring bug. produces and consumes are part of the mapping key; a mismatch is no handler, not a converter failure you can ignore.

Using HttpServletRequest.getParameter after @RequestBody consumed the stream: the body is gone. If you need both query params and a body, they are different sources. Do not parse the body twice.

Redirecting to a relative path behind a reverse proxy without forwarded headers sends users to http://internal:8080. Set the framework forwarded strategy and test with X-Forwarded-Proto.

For the room: draw Filter, DispatcherServlet, interceptor, controller, advice, view. If the boxes are in the wrong order, stop and fix that before talking about WebFlux.

How to answer in the room

Draw Filter, DispatcherServlet, HandlerMapping, interceptor, controller, HttpMessageConverter, @ControllerAdvice. If any box is missing or out of order, fix the drawing before you talk about WebFlux. MVC interviews still fail people who skip the front controller.

Return a typed body, not Map<String,Object>. A record or DTO is an API. A map is a bag. Version with a header or a URL prefix if you cannot break clients. produces and consumes are part of the mapping key; a 415 is a mismatch, not a converter bug you ignore.

Validation belongs on the input type with @Valid and a BindingResult or an advice that turns MethodArgumentNotValidException into 400. Do not validate with if-null-throw in every method unless the rule cannot be expressed as a constraint.

Exception handling: one @ControllerAdvice that returns a stable error JSON. Controller-local @ExceptionHandler is for a special case. A forgotten advice is why one endpoint returns JSON and another returns a container HTML page. Test the advice with MockMvc.

Redirects behind a proxy need forwarded headers. If you have seen a Location: http://internal:8080, you have the story. Static resource 404s never hit an interceptor; a correlation Filter still should.

File upload, multipart, and streaming are mid-level extras. Know MultipartFile versus streaming a Resource. Do not load a 2GB file into a byte[]. If they ask about SSE or WebSocket, say those are different stacks and do not pretend @GetMapping returns an event stream without extra config.

Content negotiation is Accept plus produces, not a hidden view name. If you still return a view name string from a @RestController, you have mixed programming models. Pick one: @Controller plus a view, or @RestController plus a body.

If the interviewer hands you a controller that returns String view names from a class annotated @RestController, say the annotations disagree. @ResponseBody is already on the type. A view name becomes a string body. That is a ten-second tell that the author copied two tutorials into one class. Ask whether the method should return a DTO or a view; pick one model and delete the other annotation.

Interview questions

1. Can we have multiple Spring configuration files in Spring MVC?

Yes, we can have more than one spring context files. The following are the 2 ways to configure multiple context files.

Read full answer

2. How to enable browser caching of static resources (JS, CSS) with Spring MVC?

Using mvc:resources tag we can specify the cache period. <mvc:resources mapping= "/resources/**" location= "/WEB-INF/resources/" cache-period= "31556926" /> Also mvc:interceptor can be used to specify the cache settings.

Read full answer

3. What is DispatcherServlet in Spring MVC Framework?

Spring web MVC framework is request-driven, flows through the central Servlet, DispatcherServlet that handles all the HTTP requests and responses. Spring's DispatcherServlet is completely integrated with the Spring IoC container so it allows you to use every feature that Spring...

Read full answer

4. What is ModelAndView in Spring MVC Framework?

ModelAndView holds the view name plus the model map a controller returns. Spring resolves the view and binds model attributes for rendering.

Read full answer

5. How do I configure JNDI DataSource in Spring Web Application?

To use the servlet container configured JNDI DataSource, we need to wire it in the spring bean configuration file and then inject it to spring beans as dependency. Once done, we can use it with JdbcTemplate to perform database operations....

Read full answer

6. Advantages of Spring MVC over Struts.

Spring provides an integrated framework for all tiers of your application. Spring provides a very clean separation between controllers, JavaBean models, and views....

Read full answer

7. Use of BindingResult interface in Spring MVC.

Use a BindingResult object as an argument to the validate method of a Validator inside a Controller and the BindingResult object will hold the validation errors. validator.validate(modelObject, bindingResult); if (bindingResult.hasErrors()) { // Handle error }

Read full answer

8. Advantages of Spring MVC framework over other MVC framework.

Clear separation of roles. Model, controller, validator, command object, form object, DispatcherServlet, handler mapping, view resolver, etc.

Read full answer

Next in this series: Hibernate interview questions
«
»

Comments & Discussions