通过post方法将json字符串发送到服务器

时间:2013-11-21 15:03:26

标签: java ajax json servlets post

我尝试了很多我在这里找到的例子,但没有一个对我有用,我在服务器端得到错误或null对象。这是在客户端:

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

服务器端:

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>

}

1 个答案:

答案 0 :(得分:3)

你的错误在这里:

contentType: "application/json",

这是错误的。当您打算在servlet中使用request.getParameter()和朋友时,它会期望内容类型为application/x-www-form-urlencoded,这恰好是HTML的{strong>默认内容类型{{1}和jQuery <form>

摆脱错误的内容类型说明。