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?
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
.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With