廢話不多說,直接改原來的程序就可以了,使用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框架來說肯定差不少,但是目前而言還是個不錯的解決方案。