Jakarta REST resources and Spring MVC controllers
Compare Jakarta REST and Spring MVC routing, resource scopes, serializers, and exception mapping with Java examples for the same HTTP API.
A Jakarta REST resource and a Spring MVC controller can expose the same endpoints. I compare their route matching, serialization, and exception handling to clarify what changes when the runtime changes.
The examples use Java 21, Jakarta REST 3.1 with Quarkus REST, and Spring Boot 3.4 with Spring MVC 6.2.
How Jakarta REST routes a request
JAX-RS specifies a portable API for Java HTTP resources. JSR 370 described JAX-RS 2.1, and its successor now uses jakarta.ws.rs. The implementation selects a resource method based on the URI, HTTP method, and media types. A representation provider reads or writes the payload, while filters and interceptors run around the selected resource at defined points.
flowchart TD
Req["HTTP Request"] --> ReqFilter["ContainerRequestFilter"]
ReqFilter --> Match["URI / Method Matching"]
Match --> Reader["MessageBodyReader"]
Reader --> Resource["Resource Method (@Path / @GET)"]
Resource -->|"Success"| Writer["MessageBodyWriter"]
Resource -->|"Exception"| ExMapper["ExceptionMapper"]
ExMapper --> Writer
Writer --> ResFilter["ContainerResponseFilter"]
ResFilter --> Res["HTTP Response"]
Exposing the same route in two frameworks
| Concern | Jakarta REST | Spring MVC |
|---|---|---|
| Route | @Path and @GET, @POST, or other verbs | @RestController and mappings such as @GetMapping |
| Media type | @Consumes and @Produces | consumes and produces |
| Response wrapper | Response | ResponseEntity<T> |
| Serialization SPI | MessageBodyReader and MessageBodyWriter | HttpMessageConverter |
| Filtering | Container filters and reader/writer interceptors | Servlet filters and MVC interceptors |
| Exception handling | ExceptionMapper<T> in a provider | @ExceptionHandler and @RestControllerAdvice |
| Typical lifetime | Default standard resource lifetime is per request | A controller is generally a singleton bean |
The resource and provider examples use Jakarta REST. The equivalent MVC example uses Spring’s route and response types.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// src/main/java/com/example/jaxrs/OrderResource.java
package com.example.jaxrs;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.net.URI;
@Path("/api/orders")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class OrderResource {
public record OrderRequest(String itemId, int quantity) {}
public record OrderResponse(String orderId, String itemId, int quantity) {}
@GET
@Path("/{orderId}")
public Response getOrder(@PathParam("orderId") String orderId) {
if ("unknown".equals(orderId)) {
throw new OrderNotFoundException(orderId);
}
return Response.ok(new OrderResponse(orderId, "ITEM-1", 2)).build();
}
@POST
public Response createOrder(OrderRequest request) {
String newId = "ORD-2026";
return Response.created(URI.create("/api/orders/" + newId))
.entity(new OrderResponse(newId, request.itemId(), request.quantity()))
.build();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// src/main/java/com/example/jaxrs/OrderProviders.java
package com.example.jaxrs;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
class OrderExceptionMapper implements ExceptionMapper<OrderNotFoundException> {
@Override
public Response toResponse(OrderNotFoundException ex) {
return Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON)
.entity(Map.of("error", "ORDER_NOT_FOUND", "orderId", ex.getOrderId()))
.build();
}
}
@Provider
class RequestLoggingFilter implements ContainerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class);
@Override
public void filter(ContainerRequestContext ctx) {
log.info("JAX-RS Request: {} {}", ctx.getMethod(), ctx.getUriInfo().getPath());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// src/main/java/com/example/mvc/OrderController.java
package com.example.mvc;
import java.net.URI;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
public record OrderRequest(String itemId, int quantity) {}
public record OrderResponse(String orderId, String itemId, int quantity) {}
@GetMapping("/{orderId}")
public ResponseEntity<OrderResponse> getOrder(@PathVariable String orderId) {
if ("unknown".equals(orderId)) {
throw new OrderNotFoundException(orderId);
}
return ResponseEntity.ok(new OrderResponse(orderId, "ITEM-1", 2));
}
@PostMapping
public ResponseEntity<OrderResponse> createOrder(@RequestBody OrderRequest request) {
String newId = "ORD-2026";
return ResponseEntity.created(URI.create("/api/orders/" + newId))
.body(new OrderResponse(newId, request.itemId(), request.quantity()));
}
}
@RestControllerAdvice
class OrderExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<Map<String, String>> handleNotFound(OrderNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", "ORDER_NOT_FOUND", "orderId", ex.getOrderId()));
}
}
Framework-managed scopes can override the default lifetime. Avoid storing per-request information in fields on an object shared by multiple requests. Use method parameters or a request-scoped dependency instead.
Selecting the runtime for a service
When I already use Spring Boot’s data, security, and validation stack, MVC is a straightforward starting point. Jakarta REST fits a Jakarta EE or Quarkus deployment that uses its providers and CDI integration. Framework-specific extensions can limit portability even when the annotations on the resource are standard. Identify those dependencies before moving a module.
Preserving exceptions and media type contracts
A broad ExceptionMapper can catch a WebApplicationException and change an HTTP status the runtime set intentionally. Scope a mapper to the failures it owns, or return the existing response when appropriate.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Provider
public class GlobalExceptionMapper implements ExceptionMapper<Throwable> {
@Override
public Response toResponse(Throwable ex) {
if (ex instanceof WebApplicationException webEx) {
return webEx.getResponse();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.APPLICATION_JSON)
.entity(Map.of("error", "INTERNAL_SERVER_ERROR"))
.build();
}
}
A selected resource can return a Java object for which the runtime has no suitable provider. That failure appears when the server tries to write the response.
1
2
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:
MessageBodyWriter not found for media type=application/json, type=class com.example.OrderResponse
Check the media types on the request and on the selected resource. Content-Type describes the submitted representation. Accept expresses the representations the client will read. Mismatches should produce the status and body the contract defines, including 415 or 406 where applicable.
Testing the runtime boundary
Run POST and GET against the actual server so provider discovery and exception resolution run. Include a normal record, an absent record, a deliberately unsupported request type, and a response type the resource cannot provide. Compare status, content type, and body before replacing the implementation.