我有一个返回json / xml的rest应用程序。我使用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
}
答案 0 :(得分:3)
如果您不希望表单返回到视图,则无需使用@ModelAttribute注释表单,即使没有@ModelAttribute注释,它也会干净地绑定到SourceBundleRequest
。
现在,使用Spring MVC返回JSON / XML响应的标准方法是直接返回类型(在您的情况下为PaginatedResponse
),然后使用@ResponseBody
注释方法,这是一个基础{然后,{1}}会根据客户端的Accept标头将响应转换为XML / JSON。
HttpMessageConverter
答案 1 :(得分:1)
不知怎的,我错过了最明显的解决方法。我专注于属性,忘记了我可以修改底层Map。
// Remove the form object from the model map.
model.remove("form");
如Biju建议的那样省略@ModelAttribute可能会更有效,然后删除sourceBundleRequest对象。我怀疑@ModelAttribute会有一些额外的开销。
答案 2 :(得分:0)
如何使用@JsonIgnore?
@ModelAttribute("foo")
@JsonIgnore
public Bar getBar(){}
Haven没有测试过这个