Java – Form Post with RequestBuilder

gwtjava

What is the correct way to do a RequestBuilder in GWT to be able to do exactly what this does for plain HTML:

<form action="javascript:;" method="post" data-field="form">
      <input class="rounded" name="username" size="20" type="text" data-field="username">
      <input class="rounded" name="password" size="20" type="password" data-field="password">
      <button class="submit" type="submit" value="Login" data-field="button"><br>
</form>

Best Answer

Although you can wrap each input with gwt widgets, in the case of large forms it is better to iterate over all form elements, read their names and values, and produce a query-string to send as data with your requestBuilder, this code should work:

  String payload = "";
  Element e = DOM.getElementById("form");
  // you need make this recursive if you want grand-children
  for (int i = 0, l = e.getChildCount(); i < l; i++) {
    Element c = e.getChild(i).cast();
    if (c.getTagName().toLowerCase().matches("input")) {
      String name = c.<InputElement>cast().getName();
      String value = c.<InputElement>cast().getValue();
      payload += name + "=" + value + "&";
    }
  }

  RequestBuilder b = new RequestBuilder(POST, "/my_servlet");
  try {
    b.sendRequest(payload, new RequestCallback() {
      public void onResponseReceived(Request request, Response response) {
         String resp = response.getText();
      }
      public void onError(Request request, Throwable exception) {
      }
    });
  } catch (RequestException ex) {
    ex.printStackTrace();
  }

But, I prefer to make use of the gwtquery slogan: (do more, write less):

  Properties data = Properties.create();
  // This loop also gets grand-children, and you can use more sophisticated css selectors
  for (Element e: $("form").find("input").elements()) {
    data.set($(e).attr("name"), $(e).val());
  }

  GQuery.post("/my_servlet", data, new Function(){
    public void f(){
      // Use getDataObjet in non snapshot versions
      String response = arguments(0);
    };
  });
Related Topic