简体   繁体   中英

Getting Ajax parameter from inside Java servlet

my data:

var test = {cars : []};

var cars = []
cars.push({
    "name" : "Ford",
    "year" : "2000"
});

    cars.push({
    "name" : "Audi",
    "year" : "2002"
});

test.cars = cars;   

var json = JSON.stringify(test);

$.get('/myservlet/', json, function(data) { // also tried .getJSON , .post
            alert('Success');                               
})

In Java I get the "json" variable as parameter key, but no value.

public void doPost(...) // TRIED BOTH
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {           
    for(Object a : req.getParameterMap().keySet()) {
        System.out.println(a + " - " + req.getParameter((String)a));
    }
//prints out
{"cars":[{"name":"Ford","year":"30"},{"name":"Audi","year":"2002"}]} - 

This is unusable result, because the key is always changing, and is ridiculous to for-loop the params everytime. I need to have a specific key : req.getParameter("cars")

Change it to:

$.get('/myservlet/', 'cars='+ json, function(data) { // also tried .getJSON , .post
        alert('Success');                   

You shouldn't have stringified the JSON at all. The whole JSON object test is supposed to be treated as the request parameter map. Just pass the JSON object unmodified.

$.get('/myservlet/', test, function(data) {
    // ...
});

This way it's available in the servlet as follows:

for (int i = 0; i < Integer.MAX_VALUE; i++) {
    String name = request.getParameter("cars[" + i + "][name]");
    if (name == null) break;
    String year = request.getParameter("cars[" + i + "][year]");
    // ...
}

Update Your question could be possible duplicate of READ JSON String in servlet

Previous answer

I assume you are trying to post JSON to the servlet, if thats the case read on.

You would have to check for request body instead of request parameter. Something like

BufferedReader buff = req.getReader();

Check if this works for you

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
  BufferedReader buff = req.getReader();
  char[] buf = new char[4 * 1024]; // 4 KB char buffer
  int len;
  while ((len = reader.read(buf, 0, buf.length)) != -1) {
   out.write(buf, 0, len);
  }
}

Note that I have checked the above code for syntax errors. I hope you get the idea.

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