2016-07-14 52 views
-1

發送JSON我寫這個servlet:通過AJAX請求和servlet的我回報他們從servlet的

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    response.setContentType("application/json"); 

    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); 
    String json = ""; 
    if(br != null){ 
     json = br.readLine(); 
    } 

    PrintWriter out = response.getWriter(); 

    out.write(json); 
    out.flush(); 
} 

發送數據。 的問題是,當我試圖讓我返回內部的servlet創建一個JSONObject給了我錯誤500

,讓我這個錯誤代碼:

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 




    response.setContentType("application/json"); 

    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); 

    JSONObject json = new JSONObject(); 

    json.put("name", "federico"); 

    PrintWriter out = response.getWriter(); 

    out.print(json); 
    out.flush(); 
} 

我requestAjax是:

$.ajax({ 
       url: "ValidServlet", 
       type: 'POST', 
       data : JSON.stringify(submitFormData), 
       success: function (data) { 
        alert(data.name); 
       }, 
       error: function (data) { 
        alert('error'); 
       } 
      }); 

我的錯誤是:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) (17:33:34:492 | error, network)at http://localhost:8080/ProgettoProsa/ValidServlet> 

也許我wron g返回所以json?

幫我找出我失敗的地方。

謝謝大家。

+0

能否請您指定要接收,以及你發送請求的錯誤? –

回答

0

試試這個代碼與HTTP發送JSON數據:

 
    package com.nl.services.ws.sincronizacao;

import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; @WebServlet(value = "/TestGsonHttp") public class TestGsonHttp extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Your class MyJson m = new MyJson(); m.setName("frederico"); Gson g = new Gson(); String jsonResult = g.toJson(m); PrintWriter writer = resp.getWriter(); writer.print(jsonResult); writer.flush(); writer.close(); } class MyJson { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } }

+0

是的,現在它的工作非常感謝 –