我有一個返回json/xml的休息應用程序。我使用傑克遜和jaxb進行轉換。有些方法需要接受一個query_string。我用@ModelAttribute將query_string映射到一個對象中,但是這會強制該對象進入我的視圖。我不希望該對象出現在視圖中。從視圖中省略ModelAttribute
我想我需要使用@ModelAttribute以外的東西,但我不知道如何做綁定,但不能修改視圖。如果省略@ModelAttribute註釋,則該對象作爲變量名稱出現在視圖中(例如:「sourceBundleRequest」)。
示例URL:
http://localhost:8080/rest/sourcebundles/?updateDate=20100501&label=urgent
控制器的方法:
@RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
public String getAll(@ModelAttribute("form") SourceBundleRequest sourceBundleRequest, BindingResult result, ModelMap model) throws ApiException {
// Detect and report errors.
if (result.hasErrors()) {
// (omitted for clarity)
}
// Fetch matching data.
PaginatedResponse<SourceBundle> sourceBundleResponse = null;
try {
int clientId = getRequestClientId();
sourceBundleResponse = sourceBundleService.get(clientId, sourceBundleRequest);
} catch (ApiServiceException e) {
throw new ApiException(ApiErrorType.INTERNAL_ERROR, "sourceBundle fetch failed");
}
// Return the response.
RestResponse<PaginatedResponse> restResponse = new RestResponse<PaginatedResponse>(200, "OK");
restResponse.setData(sourceBundleResponse);
model.addAttribute("resp", restResponse);
// XXX - how do I prevent "form" from appearing in the view?
return "restResponse";
}
示例輸出:
"form": {
"label": "urgent",
"updateDate": 1272697200000,
"sort": null,
"results": 5,
"skip": 0
},
"resp": {
"code": 200,
"status": "OK",
"data": {
"totalAvailable": 0,
"resultList": [ ]
}
}
所需的輸出:
"resp": {
"code": 200,
"status": "OK",
"data": {
"totalAvailable": 0,
"resultList": [ ]
}
}
的省略@ModelAttribute(「形式」)
如果我只是省略@ModelAttribute(「形式」),我仍然得到不良反應,但進入的形式是由對象名稱命名。響應看起來是這樣的:
"resp": {
"code": 200,
"status": "OK",
"data": {
"totalAvailable": 0,
"resultList": [ ]
}
},
"sourceBundleRequest": {
"label": "urgent",
"updateDate": 1272697200000,
"sort": null,
"results": 5,
"skip": 0
}
不幸的是,簡單地忽略@的ModelAttribute不會爲我工作。我已經用細節更新了OP。目前我不希望下載@ ResponseBody路線。我喜歡我的顯式視圖映射,不想進入Accept頭問題。 –