2013-05-28 28 views
0

我有一個REST API,到現在爲止總是返回JSONP(包裹在任何函數調用客戶希望JSON數據):如何在Spring MVC控制器中動態設置內容類型(取決於請求參數的存在)?

static final String JAVASCRIPT = "application/javascript;charset=UTF-8"; 

@RequestMapping(value = "/matches", produces = JAVASCRIPT) 
@ResponseBody 
public String matches(@RequestParam String callback) { 
    String json = jsonService.getCachedJson("/matches"); 
    return toJsonp(callback, json); 
} 

現在,一切都變了,這樣我需要返回JSON或JSONP:如果客戶端提供回調函數名稱,則返回JSONP和其他純JSON。

關於內容類型,我希望儘可能地正確,並且use application/json for JSON and application/javascript for JSONP

所以,這樣的事情:

@RequestMapping(value = "/matches") 
@ResponseBody 
public String matches(@RequestParam(required = false) String callback) { 
    String json = jsonService.getCachedJson("/matches"); 

    // TODO: if callback == null, set content type to "application/json", 
    // otherwise to "application/javascript" 

    return jsonOrJsonp(callback, json); 
} 

String jsonOrJsonp(String callback, String json) { 
    return Strings.isNullOrEmpty(callback) ? json : toJsonP(callback, json); 
} 

貌似我可以不再使用的@RequestMappingproduces屬性。什麼是最簡單的在上面的場景中用Spring MVC設置內容類型的方法?

我想避免定義HttpMessageConverters(或其他Spring的麻煩)或更改方法返回類型,如果可能的話!顯然,我不喜歡重複的方法聲明,其中produces值是唯一重要的區別。我正在尋找的是最小變化到上面的代碼。

最新的春天(3.2.3)。

回答

0

您是否嘗試過使用兩個請求處理程序方法?

@RequestMapping(value = "/matches", produces = JAVASCRIPT, params="callback") 
@ResponseBody 
public String Jsonp(@RequestParam String callback) { 
    return toJsonp(callback, jsonService.getCachedJson("/matches")); 
} 

@RequestMapping(value = "/matches", produces = JSON) 
@ResponseBody 
public String json() { 
    return toJson(jsonService.getCachedJson("/matches")); 
} 

params參數的第一種方法將只被映射到其中callback參數是本請求。

+0

當然,這是可能的,但不是很優雅。正如我在這個問題中寫道:「顯然,我不喜歡重複的方法聲明,其中」產生「值是唯一顯着的區別。」 – Jonik

+0

對不起,我沒有很好地閱讀你的文章。看看[這篇文章](http://www.iceycake.com/2012/06/xml-json-jsonp-web-service-endpoints-spring-3-1/)和[這篇文章](http:// blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/#comment-171228)。希望那些更有幫助。 –

相關問題