2013-07-19 42 views
4

我必须阅读客户端使用Spark(Java框架)发送的一些数据。如何读取客户端使用Spark发送的数据?

这是客户的发布请求的代码。我正在使用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; 
     } 
    }); 

我使用的火花,所以我只需要定义的路由。 我想在数据库中存储客户端发送的数据,但所有属性都为空。

我认为这种方式是不正确的。我怎样才能读取发送的数据?

回答

7

他们的方式发送数据,使用HTTP POST,你张贴JSON作为请求,还不如要求属性。这意味着您不应该使用request.attribute("item")和其他,而是将请求主体解析为Java对象。您可以使用该对象创建element并使用DAO存储它。

1

尝试使用request.queryParams(“item”)等。

3

你需要这样的事情:

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); 
    } 

} 
0

假设这是我送在我的请求,JSON

{ 'name': 'Rango' } 

这是我是如何配置我的控制器解析请求主体。

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); 
    } 
相关问题