2017-02-14 4 views
1

私は現在spring mvcアプリケーションを開発中ですので、JSON arrayを投稿する必要があります。jqueryでjavaサーブレットにjson配列を投稿するには

私はのparam attibuteをフェッチするためにrequest.getParameter("paramValue")にアクセスし、それはここで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") 
を使用することができますこれを使って、10

代わり

req.getParameterValues("test") 
+0

それでもnull値を表示します –

+0

@SelvaduraiHandeeban私はコードを更新しました –

0

次のことができます。

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

ライブラリジャクソンを追加します。

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を作成します。

コントローラ内でこのメソッドを追加します。

@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を処理します

これは今では動作します:)

関連する問題