从servlet发送json

时间:2016-07-14 14:43:14

标签: java json ajax servlets jsonobject

我写这个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();
}

通过ajax请求发送数据,servlet返回它们。 问题是,当我试图让我返回一个在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> 

也许我错了回到json?

帮我弄清楚我失败的地方。

谢谢大家。

1 个答案:

答案 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; } } }