2013-11-21 95 views
1

我嘗試了很多我在這裏找到的例子,但沒有爲我工作,我得到錯誤或服務器端的一個null對象。這是在客戶端:通過post方法發送json字符串到服務器

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> 

}

+0

你可以顯示'jsonManual'看起來像什麼嗎? – Bizmarck

+1

試試'data:jsonManual'和'Content-Type:text/html'並在服務器端'request.getContent()'。 – marekful

+0

@BharathRallapalli雙引號在JavaScript對象字面量中沒有區別。 –

回答

3

你的錯誤是在這裏:

contentType: "application/json", 

這是不對的。當您打算在小服務程序中使用request.getParameter()和朋友時,它預計的內容類型爲application/x-www-form-urlencoded,這恰好是默認內容類型的HTML <form>和jQuery $.ajax()

只是擺脫錯誤的內容類型的指令。

+0

我試了一大堆不同的組合!刪除contenttype沒有解決它。當我替換後得到它的工作,但發佈給我null – user2308321

+0

我的答案是基於迄今在問題中提供的信息(以及假設'doPost()'立即調用'processRequest()')。如果您在代碼中修改了與問題中的代碼相比較的內容,那麼確實不能保證我的答案是有效的。至少,當我複製你的代碼並刪除了'contentType'選項時,它對我有效(例如:參數是**不是**'null')。以後在servlet代碼中可能遇到的任何問題(例如,將獲得的參數解析爲JSON)完全不相關,應該在新問題中提出。 – BalusC

+0

我之前在這裏問的意思是我嘗試過,沒有contenttype和許多其他的東西,現在用我在這裏發佈的contenttype移除的同樣的東西,我仍然得到null。相同的servlet。 – user2308321

相關問題