JavaFX与后台交互----通过JSON
之前写了关于JavaFX与后台通信的blog,里面只提交了一个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(); } } ] } ] }}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(); }}