How to read data sent by the Client using Spark?

I need to read some data sent by the client using Spark (Java framework).

This is the client request code. I am using jQuery.

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

Server Code:

 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 use Spark, so I need to determine the route. I would like to store data sent by the client in the database, but all attributes are null.

I think this way is wrong. How can I read the sent data?

+4
source share
4 answers

As you send your data using HTTP POST , you send JSON as a body request, not as request attributes . This means that you should not use request.attribute("item") and others, but instead analyze the body of the request for a Java object. You can use this object to create an element and save it using the DAO .

+7
source

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); } } 
+3
source

try using request.queryParams ("item") and so on.

+1
source

Assuming this is JSON, I submit my request

  { 'name': 'Rango' } 

This is how I configured my controller to parse the request body.

  public class GreetingsController { GreetingsController() { post("/hello", ((req, res) -> { Map<String, String> map = JsonUtil.parse(req.body()); return "Hello " + map.get("name") + "!"; }))); } } public class JsonUtil { public static Map<String, String> parse(String object) { return new Gson().fromJson(object, Map.class); } 
0
source

Source: https://habr.com/ru/post/1492260/


All Articles