Inconsistent Query Parameter Conversion When Mapping Multiple Values to a Single Parameter #34613
Labels
in: web
Issues in web modules (web, webmvc, webflux, websocket)
status: declined
A suggestion or change that we don't feel we should currently apply
There is a significant inconsistency when converting a query parameter from a collection to a single value. In the following example controller, the value received by the method varies unpredictably when multiple values are provided, leading to inconsistent behavior.
If you send a
/myIntegerParam?param=1¶m=2
request, theprintIntegerParameter()
method will only receive the first value1
.But if you send a
/myStringParam?param=1¶m=2
request, theprintStringParameter()
method will receive both values comma separated as a single string:1,2
The reason why this is happening is because in the 1st case the conversion is handled by the
org.springframework.core.convert.support.ArrayToObjectConverter
class, while in the 2nd by theorg.springframework.core.convert.support.ArrayToStringConverter
class.I'm not sure whether this is a deliberate design decision or simply Spring delegating the conversion in its standard way. However, for a query parameter, this behavior introduces several issues:
Inconsistency – This approach is inconsistent with how other types are handled (e.g., integers in my example). For most types, Spring keeps only the first value, but for strings, it concatenates them. Why should a developer expect this discrepancy?
Lack of Practical Use – The resulting value is not meaningful. It is neither the first nor the last provided value, nor any actual value passed. This makes it unclear how a developer should handle it.
Incorrect Assumption – If a developer intended to get multiple values, they would have used a list rather than a single string.
Unnecessary Complexity – Given that string query parameters are extremely common, this unusual behavior forces developers to add extra validations and custom converters to ensure expected behavior.
To maintain consistency, the best approach when converting multiple query parameters into a single value is to always return the same value (either the first or last)
The above behavior was observed with:
The text was updated successfully, but these errors were encountered: