处理和服务一个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去把body直接转换为json
2、在routes中添加
POST /sayHello controllers.UserControl.sayHello()
3、打开form.scala.html
添加<script type="text/javascript" src="@routes.Assets.at("javascripts/jquery-1.9.0.min.js")"></script>
同时在routes中添加 GET /assets/*file controllers.Assets.at(path="/public", file)
注意看public\javascripts\中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());
}
}