Jsonリクエストの処理と処理
Jsonリクエストを処理する
1.UserControl.javaを追加します
//json使用
@BodyParser.Of(BodyParser.Json.class)
public static Result sayHello() {
JsonNode json = request().body().asJson();
String name = json.findPath("name").getTextValue();
if(name == null) {
return badRequest("Missing parameter [name]");
} else {
return ok("Hello " + name);
}
}
BodyParserは、playにボディを直接jsonに変換させることです
2 、追加されたルート
POST /sayHello controllers.UserControl.sayHello()
3.form.scala.htmlを開きます
追加<scripttype = "text / javascript" src = "@ routers.Assets.at(" javascripts / jquery-1.9.0.min.js ")"> </ script>
同時に、ルートにGET / assets / * file controllers.Assets.at(path = "/ public"、file)を追加します
自分のファイル名によると、 pu blic \ javascr ipt s \のjqueryがjquery-1.9.0.min.jsであるかどうかに注意してください。
form.scala.htmlファイル
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="@routes.Assets.at("javascripts/jquery-1.9.0.min.js")"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#b01").click(function(){
$.ajax({
type:'post',
url:'@routes.UserControl.sayHello',
contentType:'application/json',
data:'{"name": "Json"}',
success:function(msg){
$("#myDiv").html(msg);
},
error:function(msg){
alert(msg.statusText);
}
});
});
});
</script>
</head>
<body>
<input type="button" id="b01" value="testJson" >
<div id="myDiv">
显示区
</div>
<form action="/register" method="post">
ID:<input type="text" id="id" name="id"/>
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
応答としてJsonを使用する
sayHelloメソッドがに変更されました
//json使用
@BodyParser.Of(BodyParser.Json.class)
public static Result sayHello() {
JsonNode json = request().body().asJson();
String name = json.findPath("name").getTextValue();
ObjectNode result=Json.newObject();
result.put("stauts","OK");
result.put("name", name);
if(name == null) {
return badRequest("Missing parameter [name]");
} else {
return ok(result.toString());
}
}