我有一个返回 json/xml 的休息应用程序。我使用 jackson 和 jaxb 进行转换。有些方法需要接受一个 query_string。我已经使用 @ModelAttribute 将 query_string 映射到一个对象中,但这会强制该对象进入我的视图。我不希望对象出现在视图中。
我想我需要使用@ModelAttribute 以外的东西,但我不知道如何进行绑定,但不修改视图。如果我省略了@ModelAttribute 注释,该对象将作为变量名出现在视图中(例如:“sourceBundleRequest”)。
示例网址:
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("form")
如果我简单地省略 @ModelAttribute("form"),我仍然会得到不希望的响应,但传入的表单是由对象名称命名的。响应如下所示:
"resp": {
"code": 200,
"status": "OK",
"data": {
"totalAvailable": 0,
"resultList": [ ]
}
},
"sourceBundleRequest": {
"label": "urgent",
"updateDate": 1272697200000,
"sort": null,
"results": 5,
"skip": 0
}