我想在我的Spring控制器中使用一些Map<MyEnum, String>
作爲@RequestParam
。現在我做了以下:如何使用@RequestParam(value =「foo」)在Spring控制器中映射<MyEnum,String>?
public enum MyEnum {
TESTA("TESTA"),
TESTB("TESTB");
String tag;
// constructor MyEnum(String tag) and toString() method omitted
}
@RequestMapping(value = "", method = RequestMethod.POST)
public void x(@RequestParam Map<MyEnum, String> test) {
System.out.println(test);
if(test != null) {
System.out.println(test.size());
for(Entry<MyEnum, String> e : test.entrySet()) {
System.out.println(e.getKey() + " : " + e.getValue());
}
}
}
這種行爲很奇怪:我只是得到每個參數。所以如果我用?FOO=BAR
來調用URL,它會輸出FOO : BAR
。所以它絕對需要每個字符串,而不僅僅是MyEnum
中定義的字符串。
所以我想了一下,爲什麼不把它命名爲:@RequestParam(value="foo") Map<MyEnum, String> test
。但後來我只是不知道如何傳遞參數,我總是得到null
。
或者有沒有其他解決方案呢?
它說:如果方法的參數是Map<String, String>
或MultiValueMap<String, String>
和未指定參數名稱[...]。所以它必須是可以使用value="foo"
並以某種方式設置的值)
和:如果方法參數的類型是Map
並且指定了請求參數的名稱,則該請求的參數值被轉換爲Map
假定適當的轉換策略可用。那麼在哪裏指定轉換策略?
現在我已經建立了其作品的定製解決方案:
@RequestMapping(value = "", method = RequestMethod.POST)
public void x(@RequestParam Map<String, String> all) {
Map<MyEnum, String> test = new HashMap<MyEnum, String>();
for(Entry<String, String> e : all.entrySet()) {
for(MyEnum m : MyEnum.values()) {
if(m.toString().equals(e.getKey())) {
test.put(m, e.getValue());
}
}
}
System.out.println(test);
if(test != null) {
System.out.println(test.size());
for(Entry<MyEnum, String> e : test.entrySet()) {
System.out.println(e.getKey() + " : " + e.getValue());
}
}
}
是,如果春天可以處理這個肯定更好...
所以它真的不工作沒有轉換器?非常討厭... –
它確實如果你只是例如'@RequestParam(「foo」)MyEnum foo'。似乎只是在'Map'內部丟失。 –
我不明白這個答案如何得到3票。我試圖以非常相似的方式綁定請求參數映射。那裏我不需要'Enum'。我試圖用'@RequestParam(value =「foo」)Map foo'來獲取某些東西,但foo始終爲空。按照這個答案的建議,我的url看起來像'/ my-service?foo [1] = 2&foor [10] = 20'。 –