Search code examples
javaajaxrestlet

How to get AJAX values in Java


I'm doing an ajax call to my server, and need to get the values from it. How is this done?

This is the ajax:

$.ajax({
    type: "POST",
    url: "http://localhost:8080/myapp/etc",
    contentType: "application/json; charset=utf-8",
    data: {"id": "1", "somekey": "somevalue"},
    dataType: "json",
    async: "true",
    success: function(msg) {
        alert("success " + msg);
    },

    error: function(msg) {
        alert("error " + msg.toString());
    }
});

I'm working with Restlets so I'm assuming the values would be in the Representation entity. This is the method:

@Post
public Representation doPost(Representation entity) {
    String et = java.net.URLDecoder.decode(entity.getText(), "UTF-8");
    System.out.println("the entity text " + et);
}

This prints out "id": "1", "somekey": "somevalue". But how do I get the other values? The async, the url, etc?


Solution

  • Restlet will give you access about the elements sent within the request (URL, headers, payload) but not to client-side configuration properties to build the request.

    You can have a look at what is sent in the request for your AJAX call using tool like Chome console or Firebug.

    The property async isn't sent within the request, so you can't get it from server side. For the URL, you can use this code within a server resource:

    Reference reference = getRequest().getResourceRef();
    String url = reference.toString();
    

    For more details, have a look at javadocs for the class Reference: http://restlet.com/technical-resources/restlet-framework/javadocs/2.1/jee/api/org/restlet/data/Reference.html. This class allows you to have access to each element within it (host domain, port, path, ...).

    Hope it helps you, Thierry