2016-06-27 23 views
2

我正嘗試創建一個RESTful服務並在應用程序中遇到類型衝突。現在,我通過使用兩個不同的URL來處理這個問題,但是這導致了其他問題,並且感覺不對。具有相同URL的其餘類型,JSON或HTML表單

// Controller to get a JSON 
@RequestMapping(value = "/stuff/{stuffId}", 
     method = RequestMethod.GET, 
     produces = MediaType.APPLICATION_JSON_VALUE) 
@ResponseBody 
public stuffDto getStuff(@PathVariable String stuffId) { 
    return //JSON DTO// 
} 

// Controller to get an HTML Form 
@RequestMapping(value = "/stuff/{stuffId}/form", // <- nasty '/form' here 
      method = RequestMethod.GET) 
public String getStuffForm(@PathVariable String stuffId, ModelMap model) { 
    // Prepares the model 
    return "JSP_Form"; 
} 

而且在JavaScript端:

function loadStuffForm(url) { 
    $.ajax({ 
     type : 'GET', 
     url : url, 
     success : function(response) { 
      showStuffForm(response); 
     } 
    }); 
} 

我該如何合併兩個控制器,因此它會返回基於客戶端接受什麼合適類型的數據?默認情況下,它會返回一個JSON。我想在ajax查詢中的某處添加'text/html'來代替Form。任何想法?

+1

通過此鏈接...這是你一直在尋找:: http://stackoverflow.com/questions/3110239/multiple-response-types-with-same-rest-get – Abhishek

回答

4

您可以使用內容協商與服務器進行通信並告訴它您希望從中獲得什麼樣的響應。在您的特定情況下,您作爲使用Accept標頭的客戶端會告訴服務器提供text/htmlapplication/json。爲了實現這一點,使用兩個不同的produces與同一網址:

// Controller to get a JSON 
@ResponseBody 
@RequestMapping(value = "/stuff/{stuffId}", method = GET, produces = "application/json") 
public stuffDto getStuff(...) { ... } 

// Controller to get an HTML Form 
@RequestMapping(value = "/stuff/{stuffId}", method = GET, produces = "text/html") 
public String getStuffForm(...) { ... } 

在你請求/stuff/{id}端點,如果你在頭髮送到Accept: text/html,HTML表單將返回。同樣,您將通過發送Accept: application/json標題獲得JSON響應。

我不是JQuery專家,但您可以查看此answer瞭解如何在$.ajax請求中發送Accept標頭。

+1

作品像一個魅力, 非常感謝 :) –

相關問題