3

Spring RestTemplateで配列パラメータを送信するにはどうすればよいですか?

これはサーバー側の実装です:

@RequestMapping(value = "/train", method = RequestMethod.GET)
@ResponseBody
public TrainResponse train(Locale locale, Model model, HttpServletRequest request, 
    @RequestParam String category,
    @RequestParam(required = false, value = "positiveDocId[]") String[] positiveDocId,
    @RequestParam(required = false, value = "negativeDocId[]") String[] negativeDocId) 
{
    ...
}

これは私が試したことです:

Map<String, Object> map = new HashMap<String, Object>();
map.put("category", parameters.getName());
map.put("positiveDocId[]", positiveDocs); // positiveDocs is String array
map.put("negativeDocId[]", negativeDocs); // negativeDocs is String array
TrainResponse response = restTemplate.getForObject("http://localhost:8080/admin/train?category={category}&positiveDocId[]={positiveDocId[]}&negativeDocId[]={negativeDocId[]}", TrainResponse.class, map);

以下は、明らかに間違っている実際のリクエスト URL です。

http://localhost:8080/admin/train?category=spam&positiveDocId%5B%5D=%5BLjava.lang.String;@4df2868&negativeDocId%5B%5D=%5BLjava.lang.String;@56d5c657`

周りを検索しようとしましたが、解決策を見つけることができませんでした。任意のポインタをいただければ幸いです。

4

4 に答える 4

1

コレクションをループしてURLを作成することになりました。

Map<String, Object> map = new HashMap<String, Object>();
map.put("category", parameters.getName());

String url = "http://localhost:8080/admin/train?category={category}";
if (positiveDocs != null && positiveDocs.size() > 0) {
    for (String id : positiveDocs) {
        url += "&positiveDocId[]=" + id;
    }
}
if (negativeDocId != null && negativeDocId.size() > 0) {
    for (String id : negativeDocId) {
        url += "&negativeDocId[]=" + id;
    }
}

TrainResponse response = restTemplate.getForObject(url, TrainResponse.class, map);
于 2013-03-14T07:38:00.337 に答える
0

これを試して

からリクエスト マッピングを変更します。

@RequestMapping(value = "/train", method = RequestMethod.GET)

 @RequestMapping(value = "/train/{category}/{positiveDocId[]}/{negativeDocId[]}", method = RequestMethod.GET)

そしてrestTemplateのあなたのURL

以下の指定された形式で URl を変更します

http://localhost:8080/admin/train/category/1,2,3,4,5/6,7,8,9
于 2013-01-04T09:14:26.120 に答える