阅读来自阿贾克斯的Java Servlet发送JQuery的数据数据、Java、阿贾克斯、JQuery

2023-09-10 17:40:33 作者:与孤独合葬

下面是我的Ajax code:

Here is my Ajax code:

    var myJSONObject = {"bindings": [
                                     {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}]
                             };
    $.ajax({
        url : "ships",
        data : myJSONObject,
        success : function(data){
            GLOBAL.player.startShooting(data);
        },
        error : function(data) {
            console.log("error:", data);
        },
        dataType : "json",
        timeout : 30000,
        type : "post"
    });

和这里是我的Java Servlet code:

And here is my Java Servlet code:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    System.out.println("im in PSOT");
    System.out.println(request.getParameter("myJSONObject"));

    StringBuilder sb = new StringBuilder();
    BufferedReader br = request.getReader();
    String str;
    while( (str = br.readLine()) != null ){
        sb.append(str);
    }   
    System.out.println(sb.toString());
    response.setContentType("application/json");
    response.getWriter().write("{\"key\":\"hello\",\"key2\":\"world\"}");
}

在的Java servlet返回我的Hello World的对象,但我不能阅读的Java Servlet数据 控制台打印出以下内容:

The Java servlet returns my Hello World object, but i CANNOT read data in Java Servlet The console prints out the following:

im in PSOT
null

最后一行是从去年的println空字符串。

The last line is an empty string from last println.

我使用Tomcat 7

I am using Tomcat 7

谁能告诉我什么,我做错了,为什么我不能读取的Java Servlet数据_

Can anyone please tell me what i am doing wrong and why i cannot read data in Java Servlet_

推荐答案

参数名称不是 myJSONObject 。这是JS的变量名。参数名都,你有没有在你的JSON对象的根密钥。例如,

The parameter name is not myJSONObject. That's the JS variable name. The parameter names are all the root keys which you have there in your JSON object. E.g.

String bindings = request.getParameter("bindings");
// ...

你只需要手动进一步的解析。您可以使用谷歌GSON 这一点。

至于为何阅读未返回任何东西,这是因为请求主体可以读取和解析仅曾。任何的getParameter()通话将隐做到这一点。所以,当你调用的getParameter()在的 getReader(),你不会的能够由阅读(同​​样适用于其他的方式轮!)读取请求主体。但你并不需要也无妨。只需使用的getParameter()用正确的参数名。

As to why the Reader didn't return anything, that's because the request body can be read and parsed only once. Any getParameter() call will implicitly do that. So when you call getParameter() before getReader(), you won't be able to read the request body by the Reader (the same applies for the other way round!). But you don't need it anyway. Just use getParameter() with the proper parameter names.