1

I tried many examples I found here but none worked for me, I get error or a null object on the server side. This is on client side:

jsonManual = JSON.stringify(x);
alert('send data over: ' + jsonManual); //jasonManual is a valid json string, tested
$.ajax({
    type: "POST",
    url: "loccol", //loccol.java
    data: {jsonManual:jsonManual}, 
    dataType: "json",
    contentType: "application/json",
    success: function(data, textStatus, jqXHR){
        alert(data);
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("FAIL "+errorThrown);
    }
});

server side:

public class loccol extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(loccol.class);

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = null;

    try {
        List<LocationData> manual = new ArrayList<LocationData>();

        String jsonManual = request.getParameter("jsonManual");


        log.error("JsonManual inside servlet: " + jsonManual);

            ObjectMapper m = new ObjectMapper();
            JsonNode rootNode = m.readTree(jsonManual);  

            Iterator<JsonNode> sampleIt = rootNode.getElements();
            GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 900913);
            while (sampleIt.hasNext()) {
                log.info("Starting next sample");
                JsonNode sample = sampleIt.next();
                LocationData ld = new LocationData();//Create new object
                if (sample.get("lon") != null && sample.get("lon").isDouble() &&
                           sample.get("lat") != null && sample.get("lat").isDouble()) {//We check if sample has lon and lat value
                    Coordinate c = new Coordinate(sample.get("lon").asDouble(), sample.get("lat").asDouble());
                    ld.setPoint(gf.createPoint(c));
                }
                if (sample.get("time") != null && sample.get("time").isLong()) {
                    ld.setTime(new Date(sample.get("time").asLong()));//Gets a string value
                }
                if (sample.get("floor") != null && sample.get("floor").isDouble()) {//We check if sample has lon-value
                    ld.setFloor(sample.get("floor").asDouble());//Gets a string value
                }
                if (sample.get("accuracy") != null && sample.get("accuracy").isDouble()) {//We check if sample has lon-value
                    ld.setAccuracy(sample.get("accuracy").asDouble());
                }
                if (sample.get("type") != null) {//We check if sample has lon-value
                    ld.setType(sample.get("type").asText());//Gets a string value
                }
                if (sample.get("speed") != null) {
                    ld.setSpeed(sample.get("speed").asDouble());
                }
                if (sample.get("direction") != null) {
                    ld.setSpeed(sample.get("direction").asDouble());
                }
                if (sample.get("SomethingThatDoesntExist") != null)  {
                    log.error("This example shows that you can safely check what values a sample has");
                }
                //manual.add(ld); log.info("manual add");
                manual.add(ld); 
                log.info("manual add");

            }
        for (int i = 0; i < manual.size(); i++) {
            log.info("type in manual sample "+i+": "+manual.get(i).getType());
        }
        int experimentId = SensorTracking.persistSamples(manual, null);
        out = response.getWriter();
        out.println("{\"experimentId\":"+experimentId+"}");

    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(500);            
    } finally {
        if (out != null) {
            out.close();
        }
    }
}


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

user2308321
  • 35
  • 2
  • 8
  • can you show what `jsonManual` looks like please? – Bizmarck Nov 21 '13 at 15:06
  • 1
    Try `data: jsonManual` and `Content-Type: text/html` and on server side `request.getContent()`. – marekful Nov 21 '13 at 15:07
  • @BharathRallapalli The double quotes don't make a difference in a JavaScript object literal. – Anthony Grist Nov 21 '13 at 15:07
  • Try printing `request.getParameterMap()` and see what you get. – Lycha Nov 21 '13 at 15:12
  • 1
    check this http://stackoverflow.com/questions/3831680/httpservletrequest-get-post-data – user2005494 Nov 21 '13 at 15:13
  • I would suggest checking your browser's developer tools (install Firebug if you use Firefox and don't have it) to check what's being sent to the server when the AJAX request is made. – Anthony Grist Nov 21 '13 at 15:19
  • The `data: {jsonManual:jsonManual}` is probably wrong. The data should be a string (JSON as string) and not JSON. – kalamar Nov 21 '13 at 15:57
  • this is the json that gets to server side with get method with no problem: [ { "time": 1385122232004, "lon": 1158119.057135803, "lat": 9203398.582198633, "accuracy": 102, "type": "geoloc" }, { "time": 1385122234987, "lon": 1158118.8567607198, "lat": 9203399.651899777, "accuracy": 102, "type": "geoloc" } ] – user2308321 Nov 22 '13 at 12:14
  • the problem is I'm adding sensor data to the json so it gets huge, and get is not safe for that – user2308321 Nov 22 '13 at 12:15

1 Answers1

3

Your mistake is here:

contentType: "application/json",

This is wrong. When you intend to use request.getParameter() and friends in the servlet, then it expects a content type of application/x-www-form-urlencoded, which happens to be the default content type of HTML <form> and jQuery $.ajax().

Just get rid of that wrong content type instruction.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I tried a ton of different combinations! removing contenttype didn't solve it. when I replace post with get it works, but post gives me null – user2308321 Nov 22 '13 at 12:12
  • My answer is based on the information provided so far in the question (and the assumption that `doPost()` immediately calls `processRequest()`). If you have changed something in the code as compared to the code in the question, then there's indeed no guarantee that my answer is valid. At least, when I copypasted your code and removed the `contentType` option, then it works for me (as in: the parameter is **not** `null`). Any problem which you possibly encounter hereafter in the servlet code (e.g. parsing the obtained param as JSON) is completely unrelated and should be asked in a new question. – BalusC Nov 22 '13 at 12:26
  • I meant before asking here I tried with and without contenttype and many other things, now with the same thing I posted here with the contenttype removed I still get null. same servlet. – user2308321 Nov 22 '13 at 12:29
  • 1
    Well, the problem is not visible in the information provided so far. It works for me. Didn't you said that GET works fine? Then perhaps your `doPost()` is wrong, e.g. for some unclear reason you called `request.getReader()` or `getInputStream()` in a blind attempt to solve it without actually understanding how stuff works. You should remove those method calls accessing the request body, otherwise `getParameter()` will stop working on POST. Again, my answer is based on the code posted so far in the question and the assumption that `doPost()` does *nothing else* than invoking `processRequest()` – BalusC Nov 22 '13 at 12:32
  • I posted the whole code for server side, could you have a look please? – user2308321 Nov 22 '13 at 12:51
  • 1
    Problem is not visible in code posted so far. Do you happen to have a servlet filter or anything else which invokes `request.getReader()` or `request.getInputStream()`? That would match the problem symptom of `getParameter()` returning `null` on POST but not on GET. – BalusC Nov 22 '13 at 12:52
  • have to check that one, I'm extending this app and don't know everything about it yet, thanks for your help – user2308321 Nov 22 '13 at 12:57