Sub topic 2
How Spring Converts Strings to Java Types
Assume you know basic Java, HTTP, JSON, and how to run a Spring Boot web project. Spring MVC receives most URL values as strings. It then converts them to the Java types declared in your controller method.
Converting path and query values
@PathVariable reads a value from the URL path. @RequestParam reads a value from the query string. Spring uses its conversion system to turn values into types such as Long, int, enum, and LocalDate.
@GetMapping("/books/{id}")
public Book getBook(
@PathVariable Long id,
@RequestParam(defaultValue = "AVAILABLE") Status status,
@RequestParam
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate since) {
return service.find(id, status, since);
}
enum Status {
AVAILABLE, ARCHIVED
}For /books/42?status=ARCHIVED&since=2024-05-01, Spring converts "42" to 42L, "ARCHIVED" to Status.ARCHIVED, and "2024-05-01" to a LocalDate.
If conversion fails, such as id=abc, Spring cannot call the method normally. The request should receive a 400 Bad Request response.
Reading a request body with `@RequestBody`
A request body carries structured data, commonly JSON. @RequestBody tells Spring to read that body and create a Java object from it.
Mapping JSON with Jackson
Spring Boot uses Jackson, a JSON library, to map JSON property names to record components or class fields. A record is often a concise request DTO, or data transfer object.
public record CreateBookRequest(
String title,
String author,
int pages) {}
@PostMapping("/books")
public Book create(@RequestBody CreateBookRequest request) {
return service.create(request);
}This JSON becomes a CreateBookRequest:
{"title":"Dune","author":"Frank Herbert","pages":412}Jackson also converts JSON number, Boolean, and nested-object values to compatible Java types. The request should include Content-Type: application/json. Missing or malformed JSON causes a binding error before the controller method runs.
Exercise
What happens when /books/abc is sent to a method with @PathVariable Long id?
Show answer
Spring cannot convert abc to Long, so the method is not called and the request should return 400 Bad Request.