Sub topic 5
How Spring converts strings to Java types
This chapter assumes you can write a basic Spring Boot controller with @GetMapping, and that you have seen @PathVariable and @RequestParam. You should also know that an exception thrown in a handler method becomes an HTTP error response.
Why conversion is needed
Everything in a URL is text. In /api/books/42?page=2&active=true, the path segment 42 and the query values 2 and true are plain strings. Your controller method declares Long id, int page and boolean active. Something has to turn the text into those types before your method runs.
Spring MVC does this when it resolves each method argument. It reads the raw string, finds a converter from String to the declared parameter type, and passes the converted value to your method. If no converter fits, or the converter rejects the text, your method is never called.
This applies to @PathVariable, @RequestParam, @RequestHeader, @CookieValue and @ModelAttribute fields. It does not apply to @RequestBody. JSON bodies are handled by Jackson, which a later chapter covers.
The conversion pipeline
The central piece is the ConversionService. Spring Boot configures one for web applications that combines two kinds of components:
- A
Converter<S, T>is a one-way function from typeSto typeT. It knows nothing about locale or format. - A
Formatter<T>converts betweenStringandTand can use aLocale. Date handling is built on formatters.
You rarely call the service yourself. You only need to know what it supports and how it fails.
Built-in conversions
These work without any configuration:
| Target type | Accepted text | Notes |
|---|---|---|
| `int`, `Integer`, `long`, `Long`, `double`, `BigDecimal` | `42`, `-7`, `3.14` | Non-numeric text fails. |
| `boolean`, `Boolean` | `true`, `on`, `yes`, `1` and `false`, `off`, `no`, `0` | Case is ignored. Any other text fails. |
| `UUID` | `123e4567-e89b-12d3-a456-426614174000` | Malformed UUIDs fail. |
| Enum | The exact constant name, such as `ACTIVE` | Case-sensitive. Surrounding whitespace is trimmed. |
| `List<T>`, `Set<T>`, `T[]` | `1,2,3` or repeated `ids=1&ids=2` | Each element is converted to `T`. |
| `Optional<T>` | Any text valid for `T` | An absent value becomes `Optional.empty()`. |
| `LocalDate`, `LocalDateTime` | Only with a format | See the dates section below. |
The next example uses several of these at once. It needs only spring-boot-starter-web.
import java.util.List;
import java.util.UUID;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
enum Status { ACTIVE, ARCHIVED }
@RestController
@RequestMapping("/api/demo")
public class ConversionDemoController {
@GetMapping("/items/{id}")
public String item(@PathVariable UUID id,
@RequestParam(defaultValue = "ACTIVE") Status status,
@RequestParam(defaultValue = "false") boolean verbose,
@RequestParam(required = false) List<Long> ids) {
return "id=" + id + ", status=" + status
+ ", verbose=" + verbose + ", ids=" + ids;
}
}With this controller:
GET /api/demo/items/123e4567-e89b-12d3-a456-426614174000?status=ARCHIVED&verbose=yes&ids=1,2,3binds every value.verbose=yesbecomestrue, andidsbecomes aList<Long>containing 1, 2 and 3.?status=archivedfails, because enum matching is case-sensitive.?ids=1,twofails, becausetwois not aLong.
Note that defaultValue is also a string. Spring runs "ACTIVE" and "false" through the same converters. A default that cannot be converted fails at request time, not at startup.
Dates and times need a format
Without extra information, Spring parses LocalDate using a locale-dependent short style, such as 5/1/24 for US English. An ISO date like 2024-05-01 does not match and is rejected. You must say which format you want:
@GetMapping("/published")
public List<Book> publishedSince(
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since) {
return service.publishedSince(since);
}@DateTimeFormat accepts either an iso constant or a pattern:
@RequestParam @DateTimeFormat(pattern = "dd/MM/yyyy") LocalDate from
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime atRepeating the annotation on every parameter becomes tedious. Spring Boot lets you set the format once for the whole application in application.properties:
spring.mvc.format.date=iso
spring.mvc.format.date-time=iso
spring.mvc.format.time=isoThese settings affect only conversion of request parameters through the conversion service. They do not change how Jackson writes dates in JSON.
Absent, empty, and invalid are three different cases
Three situations look similar but behave differently.
- The parameter is absent. A required
@RequestParamthrowsMissingServletRequestParameterException, which becomes a 400 by default. Withrequired = falseor adefaultValue, there is no error. A reference type receivesnullor the default. - The parameter is present but empty, as in
?page=. For a wrapper type such asInteger, the number converter returnsnull. For a type with adefaultValue, Spring treats an empty string as missing and uses the default. For a primitive such asintwith no default,nullcannot be assigned, so Spring raises anIllegalStateExceptionand the client sees a 500. Giving primitives adefaultValue, or using the wrapper type, avoids this. - The parameter is present but wrong, as in
?page=abc. Conversion fails and Spring throwsMethodArgumentTypeMismatchException. The default response is 400.
Registering your own converter
Suppose you have a value type that wraps an ISBN and want to use it directly as a parameter:
public record Isbn(String value) {
public Isbn {
if (!value.matches("\\d{13}")) {
throw new IllegalArgumentException("ISBN must have 13 digits");
}
}
}Write a Converter<String, Isbn> and expose it as a Spring bean. Spring Boot finds Converter and Formatter beans and adds them to the web conversion service automatically:
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class StringToIsbnConverter implements Converter<String, Isbn> {
@Override
public Isbn convert(String source) {
return new Isbn(source.trim());
}
}A handler can now declare the parameter as Isbn:
@GetMapping("/by-isbn/{isbn}")
public Book byIsbn(@PathVariable Isbn isbn) {
return service.findByIsbn(isbn);
}If the constructor throws IllegalArgumentException, the conversion service wraps it, and the result is again a MethodArgumentTypeMismatchException. That means one exception handler covers built-in and custom failures.
If you do not use Spring Boot's auto-configuration, register the converter through WebMvcConfigurer:
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToIsbnConverter());
}
}Avoid registering the same converter both ways. It is harmless, but it makes the source of the behavior harder to find.
Making enums friendlier
The default enum conversion is strict. If clients may send active or Active, you have two options. You can add a converter that normalizes case:
@Component
public class StringToStatusConverter implements Converter<String, Status> {
@Override
public Status convert(String source) {
return Status.valueOf(source.trim().toUpperCase(java.util.Locale.ROOT));
}
}Alternatively, accept a String and map it yourself. The converter is usually cleaner because every endpoint that takes a Status benefits. Using Locale.ROOT matters. Without it, toUpperCase() on a Turkish-locale server turns i into a dotted capital İ and breaks names that contain that letter.
Turning conversion failures into 400 responses
Spring's default error body for a failed conversion is generic. A @RestControllerAdvice gives clients a clear message that names the offending parameter:
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@RestControllerAdvice
public class ConversionErrorHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
Class<?> required = ex.getRequiredType();
String expected = required == null ? "a valid value" : required.getSimpleName();
return ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Parameter '" + ex.getName() + "' must be " + expected);
}
}Request GET /api/demo/items/not-a-uuid and the response is a 400 with a body like:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Parameter 'id' must be UUID",
"instance": "/api/demo/items/not-a-uuid"
}Do not echo the rejected value back without thought. Reflecting raw user input in error messages can leak data into logs or into a page rendered by a client. The handler above reports only the parameter name and the expected type.
Common errors
- Dates rejected with a 400. The parameter has no
@DateTimeFormatand nospring.mvc.format.*property. Add one. - Enum value "not found". The client sent a different case. Normalize with a converter.
- 500 on an empty primitive. Use a wrapper type or a
defaultValue. - Custom converter never called. The class is not a bean, it is outside the component-scan path, or the generic types are written as
Converter<Object, Isbn>. Declare the source type asString. - Lambda converters registered by mistake. Registering
registry.addConverter(s -> new Isbn(s))loses generic type information, and Spring reports it cannot determine the types. Use a named class or the three-argument formaddConverter(String.class, Isbn.class, ...).
Exercise
A handler declares @RequestParam LocalDate since with no @DateTimeFormat and no spring.mvc.format.date property. A client sends ?since=2024-05-01 and gets a 400. What is the cause, and what are two ways to fix it?
Show answer
Spring's default date parsing uses a locale-dependent short style, so the ISO text 2024-05-01 does not match and conversion fails with a MethodArgumentTypeMismatchException. Fix it by adding @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) to the parameter, or by setting spring.mvc.format.date=iso in application.properties for every date parameter in the application.
Exercise
Write the signature of a handler for GET /api/books?status=active where Status is an enum with constants ACTIVE and ARCHIVED. Why does the call fail by default, and what single addition makes it work for all endpoints?
Show answer
public List<Book> list(@RequestParam Status status). The call fails because enum conversion is case-sensitive, so active does not match ACTIVE, and a MethodArgumentTypeMismatchException produces a 400. Registering a Converter<String, Status> bean that upper-cases the text (using Locale.ROOT) fixes it everywhere.
Exercise
What happens for @RequestParam int size with no default when the client sends ?size=, and how do you avoid it?
Show answer
The empty value converts to null, which cannot be assigned to a primitive, so Spring throws an IllegalStateException and the client gets a 500. Avoid it by declaring @RequestParam(defaultValue = "20") int size or by using Integer size and handling null.