简体   繁体   中英

How to get JSON data from POST request using Servlet

This is my code on the client side:

 $.ajax({
                    type:'POST',
                    charset:'utf-8',
                    url:'http://localhost:8180/GisProject/MainService',
                    data:JSON.stringify(params),
                    success:function(msg)
                    {
                        console.log(msg);
                    },
                    error:function(xhr,status)
                    {
                        console.log(status);
                    },      
                    contentType:"application/json"  
            });

I have previously parsed this data in Node using express.bodyParser but now I have to parse it using the servlet .I have seen people assign variables here without using JSON.stringify and getting that variable using request.getParameter(myData) .

What is the standard way of getting the JSON data into the servlet ?

And why do people seem to be sending Javascript objects with JSON embedded as a String within like data:{mydata:JSON.stringify(actualData)} ?

In case I was not being clear,I want to use the doPost method's request object to get the data I sent from the client side.

On the server side in a servlet you can read POST data payload from request.getReader()

And you can use JSON library like GSON to parse JSON. Something like:

YourClass obj = new Gson().fromJson(request.getReader(), YourClass.class)

Try this:

 $.ajax({
            type:"POST",
            url:'http://localhost:8180/GisProject/MainService',
            data:{mydata:JSON.stringify(params)},
            datatype:"json",
            success:function(msg)
            { 
               console.log(msg);
            },
            error:function(xhr,status)
            {
                 console.log(status);
             }, 
        });

you can send request and response object to doGet method and than get the json in the same way.

Way to send object to doGet

doGet(request, response); call it in to the post method.

Hope this should help for you:

var obj = jQuery.parseJSON( '{ "name": "John" }' ); alert( obj.name === "John" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM