2016-02-20 35 views
1

步驟1: Ajax請求:無法發送JSON作爲請求體彈簧控制器

$.ajax({ 
    url: "url", 
    type: "POST", 
    dataType: 'json', 
    data:{ 
    'id': '1', 
    'type': 'BOOK_VIEWED', 
    'access_token': response.response.access_token 
    }, 
    crossDomain: true, 
    success: function() { } 
}); 

步驟2執行從彈簧控制器方法之前請求 GET參數;這裏有兩個變種:

  • 變體1:如果我在頭與content-type: json發送Ajax請求,這將工作;否則會:

    String token = request.getParameter(HEADER_SECURITY_TOKEN); 
  • 變2:如果我在報頭中設置content-type: json,這將工作:

    StringBuilder sb = new StringBuilder(); 
    BufferedReader reader = request.getReader(); 
    String line; 
    while ((line = reader.readLine()) != null) 
     sb.append(line).append('\n'); 

STEP 3.春季控制器bookOpened方法應執行:

@RequestMapping(value = "/event", 
        method = RequestMethod.POST, 
         produces = MediaType.APPLICATION_JSON_VALUE) 
public void bookOpened(@RequestBody PostEvent postEvent, HttpServletRequest request) { 
    // .. 
} 

試圖運行時,不執行bookOpened方法,並且引發415(unsupported media type) Exception。如果方法簽名更改爲僅接受:HttpServletRequest request參數(不包含@RequestBody參數),它將起作用;但這對我來說不是一個可行的解決方案。

的主要問題:

  • 在步驟2中,我想獲得從請求的參數。
  • 在步驟3中,我想包括@RequestBody參數,而不僅僅是參數HttpServletRequest
+0

您是否在項目中包含了依賴項:'jackson-core'和'jackson-databin'? –

+0

你如何在**控制器之前獲得params **?用攔截器或其他方式? –

回答

0

STEP 3

要強制你請求消息變換過程中,你必須指定它的內容類型。它必須是application/json。在data請求的參數你必須發送String,但不array。所以,你的要求可能看起來如下:

var post = {}; 
post['id']=1; 
post['type']='BOOK_VIEWED'; 
post['access_token']=response.response.access_token; 

$.ajax({ 
     url: 'url', 
     type: 'post', 
     contentType : 'application/json', 
     dataType:'json', 
     data:JSON.stringify(post) 
    }) 
    success: function() { ... } 
}) 

此外,包括JSON消息變換到你的項目,你必須聲明一些依賴。如果您還沒有這樣做了,包括這依賴到你pom

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-core</artifactId> 
    <version>2.4.1</version> 
</dependency> 
<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.4.1.1</version> 
</dependency> 

STEP 2

因爲客戶端發送請求只有一次,你可以閱讀的要求只是一次體。所以,絕不要使用request.getReader(),除非在HttpMessageConverter的實現中使用它。爲了從請求中獲取價值,您可以將其作爲請求參數(查詢)發送。在你的情況下,將參數添加到URL,你必須手動編寫URL字符串:

... 

$.ajax({ 
     url: 'url?acces_token='+encodeURIComponent(response.response.access_token), 
     type: 'post', 
     contentType : 'application/json', 
     dataType:'json', 
     data:JSON.stringify(post) 
    }) 
    success: function() { ... } 
}) 

之後,你可以得到請求參數與衆所周知的,你的方法:

String token = URLDecoder.decode(request.getParameter('acces_token'), "utf-8"); 

不是,那在將它作爲url參數傳遞並在服務器端獲取它時再次對其進行解碼之前,您已對其進行編碼。

希望這會有幫助。