JSONを取り扱う為に、JAVAのライブライを追加
org.restlet.ext.json.jar :JsonRepresentationが含まれている
org.json.jar :JSONObjectが含まれている
JSONを取り扱う為に、JAVAのライブライを追加
org.restlet.ext.json.jar :JsonRepresentationが含まれている
org.json.jar :JSONObjectが含まれている
1.Formの値をJSONデータとしてPostできるようにする。
JSPの例
<body>
<form id="form-id" method="post" action="/sampleRest/rest/paramExe2" >
入力<p>
input1:<input type="text" name="input1" id="input1" value="">
</p>
input2:<input type="text" name="input2" id="input2" value="">
<a href="javascript: void(0)" id="sw">switch</a><br />
</form>
</body>
2.Formの情報をJqueryでPostするJavaScriptの関数(#swのリンクがクリックされたら)
<script type="text/javascript">
var form;
var param = {};
var json;
$(function(){
$('#sw').click(
function(){
getFormData();//FormデータをJSONデータにする
$.ajax({
type: 'post',
url: '/sampleRest/rest/paramExe3',//実行するReslretl
data: json,//送信する値(JSON)
success: function(data){
disp(data);//サーバから帰ってきたJSONデータを表示する
}
});
}
);
});
3.実行されるサーバサイドのロジック(Restlet)
@Post("Json")
public Representation handlePost2(Representation rep) throws ResourceException, IOException, JSONException {
StringBuffer sb = new StringBuffer();
JsonRepresentation jsonRep = new JsonRepresentation(rep.getText());
JSONObject object = jsonRep.getJsonObject();
if (object != null) {
Iterator<String> ite = object.keys();
while(ite.hasNext()){
String key = ite.next();
String val = object.getString(key);
System.out.println("key:"+ key);
System.out.println("val:"+ val);
}
}
Representation representation = new JsonRepresentation(jsonRep);//そのまま返却
return representation;
}
3.サーバサイドから帰ってきたJSONデータを表示する。
function disp(data){
alert('001:' + data.input1);
alert('002:' + data.input2);
}
4.Formの値をJSON形式にしてサーバに送る処理
function getFormData(){
form = $('#form-id');
$(form.serializeArray()).each(function(i, v) {
param[v.name] = v.value;
});
json = $.toJSON(param);
alert('json');
alert(json);
}