3

I am totally confused about this strange bug that I am facing in my code. So, I am trying to send data from my jQuery script to a servlet with AJAX. Now, here is the strange part that I have noticed, when I set the contentType to application/json, I notice that all the values in server side are null but the moment I remove it, I get the right data in my servlet. Now, I would like to know why am I facing such a bug?

Here is my 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 code -

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());    

    }
user1516873
  • 5,060
  • 2
  • 37
  • 56
Rachel
  • 173
  • 4
  • 12
  • you may take a look to [Retrieving JSON Object Literal from HttpServletRequest](https://stackoverflow.com/questions/1548782/retrieving-json-object-literal-from-httpservletrequest) – gaetanoM Jul 24 '17 at 13:19
  • You can open browser, press F12, run both version and check difference with content-type: `application/json` and `application/x-www-form-urlencoded` Also, please read http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String) especially ` For HTTP servlets, parameters are contained in the query string or posted form data` – user1516873 Jul 24 '17 at 13:21

1 Answers1

1

That is because when you sent the ajax request as this:

 $.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);
        }
    });

you send the data as normal POST parameters (not Stringnyfied) and you tell your servlet that this is a JSON string (Which is not!!!)

So to actually get this to work you have to either Stringnify the data you send to the servlet or to remove the contentType: "application/json" and 'dataType:'json' so you can treat the data as normal POST data.

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125