play framework2開發(四)

處理和服務一個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());
	   }
	 }
	 




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章