Reading jQuery data sent from Ajax to Java Servlet

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

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

The Java servlet returns my Hello World object, but I CAN'T read the data in the Java Servlet. The console returns the following data:

 im in PSOT null 

The last line is the empty line from the last println.

I am using Tomcat 7

Can someone tell me what I am doing wrong and why I cannot read data in Java Servlet _

+4
source share
2 answers

The parameter name is not myJSONObject . This is the name of the JS variable. Parameter names are all the root keys that you have in your JSON object. For instance.

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

You will only need to manually analyze it. You can use Google Gson for this.

As for why Reader did not return anything, this is because the request body can be read and analyzed only once . Any call to getParameter() will implicitly do this. Therefore, when you call getParameter() before getReader() , you will not be able to read the request body using Reader (the same applies to the other path!). But you do not need it. Just use getParameter() with the appropriate parameter names.

+6
source

You will only need to manually analyze it. You can use Google Gson for this.

As for why Reader did not return anything, this is because the request body can be read and parsed only once. Any call to getParameter () will implicitly do this. Therefore, when you call getParameter () before getReader (), you will not be able to read the body of the Reader request (the same applies to the other path!). But you do not need it. Just use getParameter () with the appropriate parameter names.

0
source

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


All Articles