0

I have a JSP page in which I am sending an AJAX Request to servlet having data as JSON Array. But I am getting null value in the servlet. Request.getParameter() returns null, but when i tried using a simple json object for e.g. data:{jsonData:'test'} it works for me.

Ajax Snippet

function updateStatus() {       

    var Url = {

            "Urls" : [

            {
                "Env" : "DEV : CC",
                "Url" : "https://localhost:8081/cc",
                "Status" : "Up",
                "Revision" : ""             
            }, {
                "Env" : "MO : CM",
                "Url" : "https://localhost:8082/ab",
                "Status" : "Up",
                "Revision" : ""             } ]         }


          $.ajax({
             url:'Environment',
             data:{jsonData : Url},
             type:'post',
             cache:false,
             success:function(data){
                alert('Hi');
             },
             error:function(){
               alert('error');
             }
          });

    }

Servlet function

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

        try 
        {
            String jsonString = request.getParameter("jsonData");
            JSONArray array = new JSONArray(jsonString);
            for (int i = 0; i < array.length(); i++) {
              String path = array.getString(i);
              System.out.println(path);
            }
        } 
        catch (JSONException e) 
        {
            e.printStackTrace();
        } 
DevX
  • 490
  • 6
  • 23
  • Can you try to call JSON.stringify() on the object you're posting? (data: JSON.stringify( Url )). Also, in your Servlet, you're looking for an array in "jsonString", but "jsonString" is at best an object, containing the array "Urls". – Heiko Jakubzik Dec 22 '17 at 19:52
  • Hi Heiko, I tried but didn't work $.ajax({ url:'Environment', data:JSON.stringify(Url), contentType: 'charset=UTF-8' , type:'post', cache:false, success:function(data){ alert('Hi'); }, error:function(){ alert('error'); } }); – DevX Dec 22 '17 at 20:01
  • Also i changed the servlet code String jsonString = request.getParameter("jsonData"); String[] jsonString1 = request.getParameterValues("jsonData"); – DevX Dec 22 '17 at 20:01
  • I guess jquery does the JSON.stringify automatically anyway, it was probably not a brilliant idea. In your Servlet, try JSONObject object = new JSONObject( jsonString ); JSONArray array = object.getJSONArray("Urls"); – Heiko Jakubzik Dec 22 '17 at 20:09
  • Hi Heiko, By the way this jsonString is itself null, if i pass it to JSONObject variable it will give me a null pointer exception. – DevX Dec 22 '17 at 20:21
  • Try `data:{jsonData : JSON.stringify(Url)}` instead of `data:JSON.stringify(Url)` . – Gurkan Yesilyurt Dec 22 '17 at 20:45
  • data:{'jsonData':JSON.stringify(Url)} use quotes for key since its a key – Pavan Kumar T S Dec 23 '17 at 10:58
  • If the server is not responsible to process parameters from the request then you probably have inconsistent services involved error which prevents you from getting further processing the data like validation. Nevertheless you just fail on the wrong request itself. – Roman C Dec 24 '17 at 16:28

1 Answers1

2

When you send your data, If you check the Form Data of resource Environment on a browser developer tool "Network" tab (in Chrome), you will notice that your data is being sent to server as array as follows:

jsonData[Urls][0][Env]:DEV : CC
jsonData[Urls][0][Url]:https://localhost:8081/cc
jsonData[Urls][0][Status]:Up
jsonData[Urls][0][Revision]:
jsonData[Urls][1][Env]:MO : CM
jsonData[Urls][1][Url]:https://localhost:8082/ab
jsonData[Urls][1][Status]:Up
jsonData[Urls][1][Revision]:

So, in this case, you can access each of them severally:

request.getParameter("jsonData[Urls][0][Url]");
request.getParameter("jsonData[Urls][1][Env]");

But you can use data:{jsonData : JSON.stringify(Url)} and get it by request.getParameter("jsonData"); to send valid Json string to the server side and parse it using any Json parser libs.

Note: Your json data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" not as "application/json". Therefore you can access it by request.getParameter().

Gurkan Yesilyurt
  • 2,635
  • 2
  • 20
  • 21
  • It worked for me thanks alot ! There was a another culprit, i used contentType: 'application/json'. Can you give me a small hint why it is not getting read. or how can i access it. – DevX Dec 25 '17 at 22:22