2012-08-24 24 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(){} 

沒有測試