gpt4 book ai didi

java - Spring @MatrixVariable 用于每个键单个值

转载 作者:太空宇宙 更新时间:2023-11-04 12:36:03 24 4
gpt4 key购买 nike

我正在阅读《Spring MVC,初学者指南》一书。在一节中,它建议使用矩阵变量来传递高价和低价。在他们的示例中,声明指定字符串列表作为第二个参数(见下文)。

@MatrixVariable(pathVar="price") Map<String, List<String>> priceParams

但是,由于每个键只有一个值,我想我应该尝试这样的声明:

@MatrixVariable(pathVar="price") Map<String, String> priceParams

当我尝试访问与 Map 中存储的特定键关联的“值”时(使用 iterator.getKey()iterator.getValue() ,我不断收到运行时 ClassCastException 错误。

"Request processing failed; nested exception is java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.lang.String"

我尝试过不同的数据类型,例如Integer , BigInteger , Double , Float并且错误总是相同的(除了它不是 String )

当我在调试中检查 PriceParams 时,数据类型显示为 LinkedMultiValueMap目标 map 为 LinkedHashMap .

我开始怀疑不可能使用 Map<K,V> 声明矩阵变量但只有Map<K, List<V>>

Map<K, List<V>> 的形式声明它有效,但您必须循环浏览 List 中的所有条目,即使只有一个存在。

如有任何帮助,我们将不胜感激

最佳答案

来自documents

If the method parameter type is Map and a matrix variable name is specified, then the matrix variable value is converted to a Map assuming an appropriate conversion strategy is available.

If the method parameter is Map<String, String> or MultiValueMap<String, String> and a variable name is not specified, then the map is populated with all matrix variable names and values.

因此您需要进行如下更新(即删除 pathVar )

@MatrixVariable Map<String, String> priceParams

如果您仍然遇到任何问题,请在评论中告知

另请参阅 this文章以获取更多见解。

关于java - Spring @MatrixVariable 用于每个键单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37325634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com