【问题标题】:send json string to server via post method通过 post 方法将 json 字符串发送到服务器
【发布时间】:2013-12-06 03:03:41
【问题描述】:

我尝试了许多在这里找到的示例,但没有一个对我有用,我在服务器端收到错误或 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>

}

【问题讨论】:

  • 你能展示一下jsonManual 的样子吗?
  • 尝试data: jsonManualContent-Type: text/html 以及在服务器端request.getContent()
  • @BharathRallapalli 双引号对 JavaScript 对象字面量没有影响。
  • 尝试打印request.getParameterMap(),看看你会得到什么。

标签: java ajax json servlets post


【解决方案1】:

你的错误在这里:

contentType: "application/json",

这是错误的。当您打算在 servlet 中使用 request.getParameter() 和朋友时,它需要 application/x-www-form-urlencoded 的内容类型,这恰好是 HTML &lt;form&gt; 和 jQuery $.ajax()default 内容类型.

去掉那个错误的内容类型指令。

【讨论】:

  • 我尝试了很多不同的组合!删除 contenttype 并没有解决它。当我用 get 替换 post 时,它可以工作,但 post 给了我 null
  • 我的回答是基于到目前为止问题中提供的信息(以及doPost() 立即调用processRequest() 的假设)。如果与问题中的代码相比,您更改了代码中的某些内容,那么确实不能保证我的答案是有效的。至少,当我复制粘贴您的代码并删除 contentType 选项时,它对我有用(例如:参数是 not null)。您以后在 servlet 代码中可能遇到的任何问题(例如,将获得的参数解析为 JSON)都是完全不相关的,应该在新问题中提出。
  • 我的意思是在问这里之前我尝试了使用和不使用 contenttype 和许多其他东西,现在我在此处发布的相同内容删除了 contenttype 我仍然得到空值。相同的 servlet。
  • 嗯,到目前为止提供的信息中看不到问题。这个对我有用。你不是说 GET 工作正常吗?那么也许您的doPost() 是错误的,例如出于某种不清楚的原因,您在没有真正理解事物如何工作的情况下盲目地尝试解决它,而调用 request.getReader()getInputStream()。您应该删除那些访问请求正文的方法调用,否则getParameter() 将停止在 POST 上工作。同样,我的回答是基于到目前为止在问题中发布的代码以及 doPost() 除了调用 processRequest() 之外没有别的的假设
  • 到目前为止发布的代码中看不到问题。您是否碰巧有一个 servlet 过滤器或任何其他调用 request.getReader()request.getInputStream() 的东西?这将与 getParameter() 在 POST 上返回 null 而不是在 GET 上的问题症状相匹配。
猜你喜欢
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
相关资源
最近更新 更多