Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How read data sent by Client with Spark?

I have to read some data sent by Client using Spark (a framework for Java).

This is the code of client's post request. I am using jQuery.

$.post("/insertElement", 
{item:item.value, value: value.value, dimension: dimension.value });

The code of server:

post(new Route("/insertElement") {
        @Override
        public Object handle(Request request, Response response) {
            String item = (String) request.attribute("item");
            String value = (String) request.attribute("value");
            String dimension = (String) request.attribute("dimension");
            Element e = new Element(item, value, dimension);
            ElementDAO edao = new ElementDAO();
            edao.insert(e);
            JSONObject json = JSONObject.fromObject( e );
            return json; 
        }
    });

I am using Spark so I only have to define the route. I would like to store in a database the data sent by client, but all the attributes are null.

I think that this way isn't correct. How can I read the sent data?

like image 673
user2598816 Avatar asked Dec 21 '22 02:12

user2598816


2 Answers

They way you send your data, using HTTP POST, you're posting the JSON as request body, not as request attributes. This means you shouldn't use request.attribute("item") and the others, but instead parse the request body to a Java object. You can use that object to create the element and store it using the DAO.

like image 174
mthmulders Avatar answered Jan 02 '23 16:01

mthmulders


You will need something like this:

post(new Route("/insertElement") {
    @Override
    public Object handle(Request request, Response response) {

        String body = request.body();
        Element element = fromJson(body, Element.class);
        ElementDAO edao = new ElementDAO();
        edao.insert(e);
        JSONObject json = JSONObject.fromObject( e );
        return json; 
    }
});


public class Element {

    private String item;
    private String value;
    private String dimension;

    //constructor, getters and setters

}

public class JsonTransformer {

    public static String toJson(Object object) {
        return new Gson().toJson(object);
    }

    public static <T extends Object> T  fromJson(String json, Class<T> classe) {
        return new Gson().fromJson(json, classe);
    }

}
like image 38
Dherik Avatar answered Jan 02 '23 16:01

Dherik