[英]How read data sent by Client with Spark?
我必须读取客户端使用Spark(Java框架)发送的一些数据。
这是客户发布请求的代码。 我正在使用jQuery。
$.post("/insertElement",
{item:item.value, value: value.value, dimension: dimension.value });
服务器代码:
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;
}
});
我正在使用Spark,所以我只需要定义路线。 我想将客户端发送的数据存储在数据库中,但是所有属性均为null。
我认为这种方式是不正确的。 如何读取发送的数据?
他们使用HTTP POST
发送数据的方式是将JSON作为请求正文而不是作为请求属性发布 。 这意味着您不应使用request.attribute("item")
和其他方法,而应将请求正文解析为Java对象。 您可以使用该对象创建element
并使用DAO
存储。
您将需要以下内容:
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);
}
}
尝试使用request.queryParams(“ item”)等。
假设这是我在请求中发送的JSON
{ 'name': 'Rango' }
这就是我配置Controller来解析请求正文的方式。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.