2017-02-14 83 views
1

我目前正在開發spring mvc應用程序,我需要張貼JSON array如何發佈一個JSON數組的Java Servlet與jQuery

當我訪問request.getParameter("paramValue")獲取帕拉姆attibute,但它返回一個null值,

這裏是我的前端代碼:

$.ajax(url, { 
    async: true, 
    type: 'post', 
    contentType: 'application/json', 
    data: JSON.stringify({ 
     "test":"test value" 
    }) 
}).done(function (response) { 
    console.log(data); 
}).fail(function (xhr) { 
    console.log("request failed"); 
    console.log(xhr); 
}); 

這裏是我的服務器端代碼:

@RequestMapping(value = "/Products", method = RequestMethod.POST) 
public void saveProducts(HttpServletRequest req, HttpServletResponse res) throws Exception { 

    System.out.println(req.getContentType()); 
    System.out.println(req.getContentLength()); 
    System.out.println(req.getContextPath()); 
    System.out.println(req.getParameterValues("test")); 
    System.out.println(req.getMethod()); 

    StringBuilder buffer = new StringBuilder(); 
    BufferedReader reader = req.getReader(); 
    String line; 
    while ((line = reader.readLine()) != null) { 
     buffer.append(line); 
    } 
    String data = buffer.toString(); 

    System.out.println(data); 

    System.out.println(req.getParameter("test")); 
} 

的輸出是:

application/json 
22 

null 
POST 
{"test" : "Test DAta"} 
null 

我無法弄清楚怎麼回事,請幫幫我。

+0

您發送的對象,而不是參數。可能重複 – nllsdfx

+0

沒有我試圖JSON.stringify()也 –

回答

0

刪除此行對你的AJAX功能

contentType: 'application/json', 

data: { 
    "test":"test value" 
} 

替換該行

data: JSON.stringify({ 
     "test":"test value" 
    }) 

,你也可以使用

req.getParameter("test") 

代替

req.getParameterValues("test") 
+0

還是它打印出來@SelvaduraiHandeeban我已經更新了代碼空值 –

+0

請檢查 –

0

您可以使用此:

var data ={id: 1, name :'test'} 


     $.ajax(url, { 
     async: true, 
     type: 'post', 
     contentType: 'application/json', 
     data: data 
    }).done(function (response) { 
     console.log(data); 
    }).fail(function (xhr) { 
     console.log("request failed"); 
     console.log(xhr); 
    }); 

和服務器端 創建一個POJO:

public class Product{ 
    private long id; 
    private String name; 
// getters and setters 

添加庫傑克遜。

在控制器中添加這個方法:

@RequestMapping(value = "/Products", method = RequestMethod.POST) 
public RepsoneEntity<? >saveProducts(@requestBody Product pr){ 
    LOG.debug(pr.toString()); 
    return new reRepsoneEntity<Product>(pr,HttpStatus.ACCEPTED); 
} 
0

我終於修好了幾個標註和更改服務器端方法的返回類型,

​​

,我用org.json訪問解析爲文本JSON對象,GSON處理的POJO

,現在工程:)