我有一个返回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头问题。 –