Spring MVC & REST practice questions

From Spring Certified Professional (Develop) (2V0-72.22) · 43 questions on this topic

Spring MVC & REST practice questions from Spring Certified Professional (Develop) (2V0-72.22). This pack has 43 questions tagged Spring MVC & REST, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Spring MVC & REST

  1. Question 1

    How is an object returned from a @RestController method turned into the JSON response body?

    1. A. Its toString() output is written directly to the response

      Incorrect: the object's toString() output is not written directly to the response.

    2. B. An HttpMessageConverter (e.g. MappingJackson2HttpMessageConverter) serializes it, selected via content negotiationCorrect answer

      Correct: an HttpMessageConverter such as MappingJackson2HttpMessageConverter serializes the value, selected via content negotiation.

    3. C. A ViewResolver renders it through a JSP template

      Incorrect: a ViewResolver rendering a JSP is for view-based controllers, not @RestController JSON responses.

    4. D. You must call Jackson's ObjectMapper manually in each handler

      Incorrect: manually calling Jackson's ObjectMapper in each handler is unnecessary.

    Explanation

    Values returned from @ResponseBody/@RestController methods are serialized by an HttpMessageConverter chosen through content negotiation on the request's Accept header, with Jackson's converter producing JSON. View resolution applies to view-based controllers, and neither raw toString output nor manual serialization is involved.

  2. Question 2

    Given the parameter @RequestParam(defaultValue = "10") int size, what happens if the request omits the size parameter?

    1. A. size is null

      Incorrect: the default value is applied instead of null, and a primitive int could not be null anyway.

    2. B. size is bound to 10, and the parameter is treated as optionalCorrect answer

      Correct: size is bound to 10 and the parameter is treated as optional because defaultValue implies required=false.

    3. C. The request fails with HTTP 400 because @RequestParam is required

      Incorrect: supplying defaultValue makes the parameter optional, so there is no HTTP 400.

    4. D. size is bound to 0

      Incorrect: the configured default of 10 is used, not 0.

    Explanation

    Providing defaultValue implies required=false and supplies that fallback value when the parameter is absent, so the parameter binds to 10 and no error occurs. The configured default rather than zero or null is applied, and a primitive int could not hold null regardless.

  3. Question 3

    A `@RestController` handler creates a new order and must return HTTP 201 Created to the client. Which TWO approaches correctly set the 201 status on the response? Select TWO.

    1. A. Annotate the handler method with `@ResponseStatus(HttpStatus.CREATED)`Correct answer

      Correct. `@ResponseStatus(HttpStatus.CREATED)` on the handler fixes the response status to 201 whenever the method completes normally.

    2. B. Return `ResponseEntity.status(HttpStatus.CREATED).body(order)` (or `ResponseEntity.created(location).body(order)`)Correct answer

      Correct. `ResponseEntity` gives full control of status, headers, and body; building it with the CREATED status (or the `created(uri)` factory) sends 201.

    3. C. Return the plain `Order` object and rely on Spring to infer 201 because the method created something

      Spring cannot infer intent from the object; a handler that just returns a body produces 200 OK by default, not 201.

    4. D. Return the integer `201` from the handler method

      Returning an `int` would be serialized as a response body of `201` with a 200 status; the return value is the body, not the status code.

    5. E. Add `@ResponseBody` to the method so the status becomes 201

      `@ResponseBody` only routes the return value to the response body via a message converter; it has no effect on the HTTP status code (which remains 200 by default).

    Explanation

    Two idiomatic ways to send 201 are annotating the handler with `@ResponseStatus(HttpStatus.CREATED)`, which fixes the status on normal completion, and returning a `ResponseEntity` built with the CREATED status (for example via `status(HttpStatus.CREATED)` or the `created(uri)` factory), which controls status, headers, and body together. Returning a plain object or an integer only affects the body and leaves the status at the default 200, and `@ResponseBody` governs body serialization, not the status.

  4. Question 4

    In a Spring MVC application, which mechanism is responsible for turning the object returned by a `@ResponseBody` handler method into the JSON written to the HTTP response — and, in the opposite direction, for turning the request body into a `@RequestBody` parameter?

    1. A. A ViewResolver, which selects a JSON view template for the returned object and renders it.

      Confuses body serialization with view resolution. View resolution applies when a handler returns a logical view name; `@ResponseBody` deliberately bypasses view resolution and writes directly to the response.

    2. B. The HandlerMapping, which selects both the handler for the request and the serialization format for its return value.

      Overloads the role of HandlerMapping. Its single responsibility is mapping a request to a handler (plus interceptors); it plays no part in reading or writing message bodies.

    3. C. A servlet Filter registered by Spring Boot that intercepts the response after the controller returns and serializes the value it finds there.

      Misplaces the conversion outside the MVC processing pipeline. Body conversion happens inside argument resolution and return-value handling within the DispatcherServlet, not in a downstream filter.

    4. D. `HttpMessageConverter` implementations (such as a Jackson-based converter), chosen according to the request's Accept/Content-Type through content negotiation.Correct answer

      Correct: `@RequestBody` and `@ResponseBody` are both implemented by `HttpMessageConverter` instances, selected by matching the media type of the request or the negotiated response.

    Explanation

    Both `@RequestBody` and `@ResponseBody` are backed by `HttpMessageConverter` implementations, which read and write the HTTP message body for a given media type; the converter to use is chosen through content negotiation based on Content-Type and Accept. View resolution is the alternative rendering path used when a handler returns a view name, so it is not involved when the body is written directly. Mapping a request to a handler is the sole concern of HandlerMapping, and the conversion is performed inside the DispatcherServlet's handler invocation rather than by a servlet filter placed around it.

  5. Question 5

    A team builds a Spring Boot web application and packages it as an executable jar. What does Spring Boot provide inside that jar so the application can serve HTTP requests?

    1. A. An embedded servlet container (Tomcat by default) that starts automatically when the application runsCorrect answer

      Correct: spring-boot-starter-web brings in spring-boot-starter-tomcat, and Boot auto-configures and starts an embedded servlet container as part of the ApplicationContext refresh, so `java -jar app.jar` serves HTTP with no external server.

    2. B. A generated deployment descriptor that an external application server reads on startup

      Misconception that Boot still relies on a web.xml-style descriptor and an external server; an executable jar is self-contained and starts its own container, and Boot's servlet configuration is done in Java, not by a generated descriptor.

    3. C. A standalone HTTP proxy that must be started separately before the jar is launched

      Confuses a front-end proxy or load balancer with the embedded container; nothing extra needs to be launched, since the container runs inside the same JVM process as the application.

    4. D. Nothing — the jar must be copied into an existing Tomcat installation's webapps directory

      Confuses the executable jar model with traditional war deployment; only a war can be dropped into a container's webapps directory, and an executable jar is designed to be run directly.

    Explanation

    Spring Boot's web starter includes an embedded servlet container, and the auto-configuration starts it as the application context refreshes. That is what makes `java -jar app.jar` a complete, runnable web application with no external server, no deployment descriptor, and no separate process to launch first. Copying the artifact into a server's webapps directory is the war-based alternative, not how executable jars work.

  6. Question 6

    A Spring Boot 2.7 web application relies on Spring MVC's default request-path matching to route requests to its `@RequestMapping` handlers. Compared with Spring Boot 2.5, what changed by default in how incoming paths are matched against mapping patterns, and what is a practical consequence?

    1. A. Since Boot 2.6 the default `spring.mvc.pathmatch.matching-strategy` is `PathPatternParser` (replacing `AntPathMatcher`): each pattern is pre-parsed once into a reusable `PathPattern` for faster matching, and a `**` wildcard is only allowed at the end of a pattern.Correct answer

      Correct. Spring Boot 2.6 switched the Spring MVC default matching strategy to `PathPatternParser`. It compiles each mapping into a `PathPattern` once (faster at request time) and constrains `**` to the final segment, so a pattern such as `/a/**/b` that `AntPathMatcher` accepted is now rejected. Setting the property back to `ant-path-matcher` restores the old engine.

    2. B. Nothing changed: Spring MVC still uses `AntPathMatcher` by default in Boot 2.6/2.7, and `PathPatternParser` is only ever used by Spring WebFlux.

      `PathPatternParser` originated in WebFlux, but Boot 2.6 made it the Spring MVC default as well. `AntPathMatcher` is now the opt-in strategy, not the default.

    3. C. The default is still `AntPathMatcher`, but suffix pattern matching (`.*`) was re-enabled by default so `/orders` also matches `/orders.json`.

      Suffix pattern matching was deprecated and disabled by default well before this change, and `PathPatternParser` does not support it at all. The default matcher changed; suffix matching was not re-enabled.

    4. D. `PathPatternParser` must be enabled per controller with an annotation; there is no global default, so behavior is unchanged unless each controller opts in.

      The strategy is a global default controlled by the `spring.mvc.pathmatch.matching-strategy` property, not a per-controller annotation.

    Explanation

    Spring Boot 2.6 changed the default Spring MVC path-matching strategy from `AntPathMatcher` to `PathPatternParser` (property `spring.mvc.pathmatch.matching-strategy`, default `path-pattern-parser`). `PathPatternParser` compiles each mapping pattern once into a reusable `PathPattern`, which is more efficient at request time, and it restricts the `**` wildcard to the final path segment, so previously-valid patterns like `/a/**/b` are rejected. Suffix pattern matching is not supported. An application that needs the legacy engine sets the strategy back to `ant-path-matcher`.

  7. Question 7

    Which TWO statements accurately describe how `RestTemplate` handles the conversion between Java objects and the HTTP message body? (Select all that apply.)

    1. A. It delegates serialization of request bodies and deserialization of response bodies to a list of registered `HttpMessageConverter` instances.Correct answer

      Correct. The reference documentation states that `RestTemplate` uses the same `HttpMessageConverter` abstraction as Spring MVC's `@RequestBody`/`@ResponseBody` handling to convert between objects and the HTTP body.

    2. B. Which converter is chosen depends on the body's Java type and the media type of the message, such as the `Content-Type` of the response.Correct answer

      Correct. Each converter declares the classes and media types it supports, and `RestTemplate` selects the first registered converter that can read or write the given type/media type combination.

    3. C. It performs conversion with a fixed, built-in Jackson binding that cannot be replaced or extended.

      Misconception that JSON support is hard-wired. The converter list is configurable via `setMessageConverters` or the constructor, and Jackson is merely one converter registered when the library is on the classpath.

    4. D. It converts bodies only for responses; request bodies must be supplied to it as a pre-serialized `String`.

      Misconception that conversion is one-directional. `HttpMessageConverter` defines both `read` and `write`, so methods such as `postForObject` serialize an arbitrary Java object into the request body automatically.

    Explanation

    RestTemplate does not implement marshalling itself; it holds an ordered list of `HttpMessageConverter` implementations and asks them to write request bodies and read response bodies, the same abstraction the Spring MVC annotated-controller model uses. Selection is driven by the Java type involved together with the message's media type, so a JSON response and an XML response of the same target class go through different converters. Treating JSON support as a fixed, unreplaceable binding is wrong because the converter list is configurable, and treating conversion as read-only is wrong because converters both read and write, which is what lets a POST body be handed over as a plain Java object.

  8. Question 8

    What is the idiomatic way to handle exceptions across all controllers and map them to HTTP responses?

    1. A. A class annotated @ControllerAdvice (or @RestControllerAdvice) containing @ExceptionHandler methodsCorrect answer

      @ControllerAdvice centralizes @ExceptionHandler methods so exceptions from any controller are mapped to HTTP responses in one place.

    2. B. Placing @ResponseStatus on the controller class

      Class-level @ResponseStatus does not handle thrown exceptions generically; it stamps a fixed status and cannot map arbitrary exceptions to responses across controllers.

    3. C. A try/catch block duplicated in every controller method

      Duplicating try/catch in every method is repetitive and not centralized, which is exactly the boilerplate global exception handling is meant to eliminate.

    4. D. A servlet Filter that inspects every response

      A servlet Filter operates at a lower level and is not an exception-to-response mapping mechanism; it lacks the handler-method context needed to map exceptions idiomatically.

    Explanation

    The idiomatic approach is to gather exception-handling methods into a single global advice component that applies across all controllers, mapping thrown exceptions to HTTP responses in one place. This avoids repetitive per-method handling, operates at the handler level rather than the raw servlet layer, and can map arbitrary exceptions rather than stamping one fixed status.

Practise all 43 Spring MVC & REST questions

Spring Certified Professional (Develop) has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open Spring Certified Professional (Develop)

Other topics in this pack