Sending data from Javascript to Servlet

2019-09-02 14:20发布

问题:

I want to make an ajax get call to server.Till now I always used:

$.get("/FruitResults?fruit="+fruitname+"&color="+colorname,function(data){addToTables(data);},"text");

for sending parameters fruit,color.Now if I have many fruits,their color,price..

{apple:{color:red,price:30},orange:{color:orange,price:10}}

and such a big list of fruits, how shoud i send this to servlet using Ajax call., in what format? and at servlet side also, how should I retrieve the request parameters from the request object?

回答1:

Http get method is not suitable for sending complex data. Therefore, you must use post method to send a complex data from client to the server. And you can use JSON format to encode this data. Example code is as follows:

var fruits = {apple:{color:red,price:30},orange:{color:orange,price:10}};
$.post("/FruitResults", JSON.stringify(fruits), function(response) {
    // handle response from your servlet.
});

Note that, since you used the post method, you have to handle this request in doPost method of the servlet instead of doGet. To retrieve the posted data you must read the input stream of the servlet request as follows:

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  String jsonString = new String(); // this is your data sent from client
  try {
    String line = "";
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jsonString += line;
  } catch (Exception e) { 
    e.printStackTrace();
  }

  // you can handle jsonString by parsing it to a Java object. 
  // For this purpose, you can use one of the Json-Java parsers like gson**.
}

** Link for gson: http://code.google.com/p/google-gson/