在java中将json数据从Ajax发送到Servlet?

时间:2017-07-24 13:00:06

标签: java jquery json ajax servlets

我对我在代码中遇到的这个奇怪的错误感到困惑。所以,我试图将我的jQuery脚本中的数据发送到带有AJAX的servlet。现在,这是我注意到的奇怪部分,当我将contentType设置为application/json时,我注意到服务器端的所有值都为null但是当我删除它时,我在servlet中得到了正确的数据。现在,我想知道为什么我会遇到这样的错误?

这是我的jsp -

<script type="text/javascript">

$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
      event.preventDefault();
      var apiname=$("#apiname").val();
      var apiendpoint=$("#apiendpoint").val();
      var apiversion=$("#apiversion").val();
      var source=$("#source").val();


     $.ajax({
            type: "POST",
            url: "HomeServlet",
            contentType: "application/json",
            dataType:'json',
            data:{"apiname":apiname,"apiendpoint":apiendpoint,"apiversion":apiversion,"source":source},
            success: function(status){
                console.log("Entered",status);
            },
            error:function(error){
                console.log("error",error);
            },

        });
});

</script>

Servlet代码 -

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        Map<String, String> job = new LinkedHashMap<>();

        //doGet(request, response);
        JSONArray jArray = new JSONArray();

      //  response.setContentType("text/html");
        PrintWriter out= response.getWriter();
        String n = request.getParameter("apiname");
        String p = request.getParameter("apiendpoint");
        String e = request.getParameter("apiversion");
        String c = request.getParameter("source");
        String status ="091";
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("driver loaded");
            System.out.println("Driver is loaded");
            Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
            System.out.println("Connection created");
            PreparedStatement ps= ((java.sql.Connection) con).prepareStatement("insert into apiinfo(apiname,apiendpoint,apiversion,accessibility) values (?,?,?,?)");
            ps.setString(1,n);
            ps.setString(2,p);
            ps.setString(3, e);
            ps.setString(4,c);
            ps.execute();
            out.close();
            status ="000";
            con.close();
            System.out.println("Inserted");
        }
        catch(Exception e1)
        {           
            System.out.println(e1);
        }
        job.put("status",status);
        jArray.put(job); 

        System.out.println(jArray.toString());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        response.getWriter().write(jArray.toString());    

    }

1 个答案:

答案 0 :(得分:1)

这是因为当您发送ajax请求时:

 $.ajax({
        type: "POST",
        url: "HomeServlet",
        contentType: "application/json",
        dataType:'json',
        data:{"apiname":apiname,"apiendpoint":apiendpoint,"apiversion":apiversion,"source":source},
        success: function(status){
            console.log("Entered",status);
        },
        error:function(error){
            console.log("error",error);
        }
    });

你发送数据作为普通的POST参数(不是Stringnyfied),你告诉你的servlet这是一个JSON字符串(这不是!!!)

因此,要实现此功能,您必须将发送到servlet的数据Stringnify或删除 contentType:&#34; application / json&#34; & #39; dataType:&#39; json&#39; ,因此您可以将数据视为普通的POST数据。