简体   繁体   中英

Need to send json data from js to java

I have a JSON string in my javascript, I need to send this to a java class. Can I use a plain java class or is it necessary to use a servlet?

Also, How can I parse the JSON data?

My JSON data is of the following format:

 var details=   { "CustomerDetails": [{'name':'Amy','age':'23'},
{'name':'Amj','age':'25'},{'name':'Amg','age':'27'}]};

I send the json string like this:

  var jsonText = JSON.stringify(details);  

    $.post('ServletClass', jsonText);  

WEb.xml:

<servlet>
<servlet-name>ServletClass</servlet-name>
<display-name>ServletClass</display-name>
<servlet-class>java.files.ServletClass</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletClass</servlet-name>
<url-pattern>/ServletClass</url-pattern>
</servlet-mapping>

On my servlet side: I try to do a system.out.println, but get nothing, is the transfer even happening properly

package XXXX;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.files.JSONObject;
import java.files.JSONSerializer;

public class ServletClass extends HttpServlet {
  public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

  }

  public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
      //          doGet(request, response);
      //JSONArray arrayObj = new JSONArray();
      JSONObject jsonObj = new JSONObject(jsonText);
      JSONArray the_
      json_array = jsonObj.getJSONArray("CustomerDetails");
      System.out.println("FINALLY HERE");



  }
}

First of all, you JSON is incorrect. Corrected JSON:

{ "CustomerDetails": [{'name':'Amy','age':'23'},{'name':'Amj','age':'25'},{'name':'Amg','age':'27'}]}

You should use AJAX to send data to the java class if you want it to be asynchronous. You will require a servlet to accept this request, that will parse this JSON and you can follow with the necessary processing on it. Look into Jackson or GSON libraries to do JSON parsing.

The following change worked for me: fullpath=contextpath\\servletname

$.post(fullpath, {jsonText:jsonText}, function(data) {
    alert(data);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM