Search code examples
javascriptjsonservletsphantomjsvelocity

POST data as json to a Servlet not working in Phantomjs


I am facing very strange issue here. I have a servlet running on my machine which renders my web page based on some input parameters.

Now, my screen capture with PhantomJS is not working if I try to send my data as a JSON object as a POST request type. For e.g. if I try:

Client side

var data = {"op": "get"};

page.open(address, 'POST', data, function (status) {
if (status !== 'success') {
    console.log('[ERROR] :: Unable to fetch the address - ' + address + ", with data - " + data);
    phantom.exit();
} else {
    page.render(output);        
}
console.log('processing...');
});

Server side

Now, on the server side, I am using Apache Velocity View templating so I have a single method which handles both get and post like :

public Template handleRequest(HttpServletRequest request, HttpServletResponse response,
        Context context){
   System.out.println(request.getParameter("op"));
   //Always null
}

However, if I try sending my data from phantomjs as:

var data = "op=get&..."
It works

Also, at many places elsewhere in my code..I am doing Ajax POST requests to the same servlet and it works perfectly for all those request.

Would anybody explain why my servlet is not reading the JSON parameters passed from Phantomjs?


Solution

  • Servlets deal with simple request, so they only know how to parse (natively) HTTP parameters, either GET parameters from the URL, or POST parameters sent as application/x-www-form-urlencoded. Newer versions of the Servlet specification can also read multipart/form-data.

    But there's nothing about JSON mentioned either in the Servlet or the HTTP specifications. So you must use a library that knows how to parse JSON and make the resulting object available in the Velocity context.