JavaFX與後臺交互----通過JSON

之前寫了關於[url=http://ivan-pig.iteye.com/blog/361920]JavaFX與後臺通信的blog[/url],裏面只提交了一個Field的值,如果要提交兩個甚至更多的Field的值就很麻煩了(通過組裝字符串,後臺解析。)所以就想到了json,之前看網上的資料說javafx自帶了json的包,但是在javafx1.1裏面沒有找到,就找了個第三方的包org.json。

廢話不多說,直接改原來的程序就可以了,使用post提交。



import javafx.io.http.*;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.ext.swing.SwingButton;
import java.io.DataInputStream;
import javafx.scene.layout.HBox;
import javafx.ext.swing.SwingTextField;
import org.json.JSONObject;


def field:SwingTextField = SwingTextField {
columns: 10
text: "Ivan"
editable: true
}

def field2:SwingTextField = SwingTextField {
columns: 10
text: "dd"
editable: true
}

var t:String= bind field.text;
var p:String = bind field2.text;

function sendHttp(){
HttpRequest {

method:HttpRequest.POST;
location:"http://localhost:8080/JavaScriptWeb/moo";

onOutput: function(os: java.io.OutputStream) {
try {
var json:JSONObject = JSONObject{};
json.put("name1",t);
json.put("name2",p);
var temp:String = "obj={json.toString()}";
os.write(temp.getBytes());
os.flush();
} finally {
os.close();
}
}

onInput: function(is: java.io.InputStream) {
try {
def data:DataInputStream = new DataInputStream(is);
field.text = data.readLine();
} finally {
is.close();
}
}
}.enqueue();
}


Stage {
title : "Http"
scene: Scene {
width: 200
height: 200
content: [HBox{
content:[
field,field2
SwingButton {
text: "Click"
action: function() {
sendHttp();
}
}
]
}
]
}
}



代碼添加了一個Field,核心代碼在onOutput裏面,就是調用了JSONObject類的一些方法而已。實際作用就是組裝了一個如下的字符串。"obj=\{\"name1\":\"{t}\",\"name2\":\"{p}\"\}"將這個字符串提交到後臺。

package test;

import org.json.JSONObject;
import org.json.JSONException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
* Created by IntelliJ IDEA.
* User: Ivan
* Date: 2009-4-3
* Time: 19:55:13
*/
public class MooServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
doGet(request,response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
String obj = request.getParameter("obj");

JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(obj);
} catch (JSONException e) {
e.printStackTrace();
}

PrintWriter writer = response.getWriter();
try {
writer.write("Hello "+ jsonObj.getString("name1") + jsonObj.getString("name2"));
} catch (JSONException e) {
e.printStackTrace();
}
writer.flush();
writer.close();
}
}



依然是調用了JSONObject類的方法,解析出了字符串。然後返回即可。當然了,這裏你還可以組裝一個字符串返回,供前臺去解析,不囉嗦了。
此方法相對於想在成熟的java的Ajax框架來說肯定差不少,但是目前而言還是個不錯的解決方案。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章