2012-08-24 19 views
3

我有一个返回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 
} 

回答

1

不知怎的,我错过了最明显的解决方法。我专注于属性,忘记了我可以修改底层的Map。

// Remove the form object from the model map. 
    model.remove("form"); 

这可能是一个小更有效地省略@ModelAttribute作为建议的六必居,然后取出sourceBundleRequest对象。我怀疑@ModelAttribute有一些额外的开销。

3

你不需要注释与@ModelAttribute形式,如果你不想要的形式回来的观点做,就会得到干净势必SourceBundleRequest即使没有@ModelAttribute注解。

现在,返回使用Spring MVC一个JSON/XML响应一个标准方式是直接与@ResponseBody返回类型(你的情况PaginatedResponse),然后注释的方法中,然后底层HttpMessageConverter将变换响应成基于来自客户端的Accept头的XML/JSON。

@ResponseBody 
public RestResponse<PaginatedResponse> getAll(SourceBundleRequest sourceBundleRequest, BindingResult result, ModelMap model) 
... 
+0

不幸的是,简单地忽略@的ModelAttribute不会为我工作。我已经用细节更新了OP。目前我不希望下载@ ResponseBody路线。我喜欢我的显式视图映射,不想进入Accept头问题。 –

0

如何使用@JsonIgnore?

@ModelAttribute("foo") 
@JsonIgnore 
public Bar getBar(){} 

没有测试