Sub topic 5
How Spring Converts Strings to Java Types
This chapter assumes you can run a Spring Boot web project and that you know the @PathVariable and @RequestParam annotations from the previous chapters. It covers how Spring turns the text in a URL into the Java types in your method signature.
Everything in a URL is text
A path segment or a query parameter always arrives as a string. A request to /api/books/42 carries the characters 4 and 2, not a number. Before Spring calls your controller method, it converts each string to the declared parameter type.
@GetMapping("/{id}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}Here the {id} segment is converted from a string to a Long. You never call Long.parseLong yourself.
The conversion pipeline
Spring's WebDataBinder does the work. It holds a ConversionService with converters for common types. For each parameter it looks for a converter from String to the target type and applies it. If none exists, or the converter throws, the request fails before your method runs.
Types converted out of the box
| Target type | Example input | Result |
|---|---|---|
| `int`, `Long`, `double` | `42` | numeric value |
| `boolean` | `true` | `true` |
| `enum` | `FICTION` | `Genre.FICTION` (case-sensitive name match) |
| `UUID` | `123e4567-e89b-12d3-a456-426614174000` | `UUID` |
| `List<String>` | `a,b,c` | list of three elements |
Repeated parameters such as ?tag=a&tag=b also bind to a list. A comma-separated value like ?tag=a,b binds to a list as well.
Dates need a format
Spring cannot guess how a date is written. Use @DateTimeFormat to declare the pattern.
@GetMapping("/published")
public List<Book> publishedSince(
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since) {
return service.publishedSince(since);
}With this, ?since=2024-05-01 becomes a LocalDate. For a custom format, use @DateTimeFormat(pattern = "dd/MM/yyyy") instead.
Optional values and defaults
Conversion interacts with required and defaultValue. The default is a string too, so Spring converts it with the same rules.
@GetMapping
public List<Book> search(@RequestParam(required = false) String author,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return service.search(author, page, size);
}If page is absent, Spring converts "0" to the int 0.
Common failures
- Wrong number format.
/api/books/abccannot become aLong. Spring throwsMethodArgumentTypeMismatchException, which produces a 400 response by default. - Unknown enum name.
?genre=fictionfails if the constant isFICTION, because the match is case-sensitive. - Empty string for a number.
?page=is an empty string. For a primitiveintthis is a conversion error. For a wrapper type, Spring usually treats it as missing and uses null or the default. - Missing format on a date. Without
@DateTimeFormat, aLocalDateparameter may fail to convert, depending on your configuration.
The default 400 response can be replaced with a clearer one. A later chapter shows how, but here is the handler that targets this failure:
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Invalid value for parameter '" + ex.getName() + "'");
}
}Try it with curl "http://localhost:8080/api/books/abc". The response now names the id parameter.
Exercise
A controller method declares @RequestParam(defaultValue = "20") int size. A client sends GET /api/books with no size. What value does the method receive, and why does the default work even though it is written as a string?
Show answer
The method receives the int 20. The default is a string, and Spring converts it to the parameter type with the same conversion service it uses for request values.
Exercise
A client sends GET /api/books/abc to a method that takes @PathVariable Long id. Which exception does Spring raise, and which status code does the client see by default?
Show answer
Spring raises MethodArgumentTypeMismatchException, and the client receives 400 Bad Request.