Wednesday, May 30, 2012

Cross Domain JSONP ( Json with padding ) with Jquery and Servlet or JAX-WS

  • Solving Cross Domain problem using JSONP ( Json with padding ) with Jquery and Servlet JAX-WS
  • or Cross-domain communications with JSONP
  • or Cross domain jquery or cross domain Ajax
  • or java - Sending JSONP vs. JSON data
  • or JSONP javascript or Java JSONP

    Well there are several techniques to address cross domain problem. Here are few.

1. Using CORS ( Cross-Origin Resource Sharing ) where in we modify the repsonse header
Access-Control-Allow-Origin: *
The asterisk permits scripts hosted on any site to load your resources; the space-delimited lists limits access to scripts hosted on the listed servers.
Problem is CORS may not work in all browsers ( See:

2. Other option is to use some server side re-direct of the request to a servlet or a php script on your  own domain which in trun calls third party web site.
But at times we may not have this option to implment a servlet or PHP script which we can call on our domain.

3.If the third party url that you are invoking supports JSONP response then all browsers work without complaining

What is JSONP ?

- JSONP - JSon with padding. It means to your JSON response we will append the callback method name.
eg: Let say your JSON response is  {"totalInterestPmtAmt":5092.79,"totalPmtAmt":15092.79}
and lets assume the callback method name that was sent in request was  getPayment JSONP Response will be :getPayment( {"totalInterestPmtAmt":5092.79,"totalPmtAmt":15092.79} )
(However if you dont give call back method name Jquery dynamically generates a method name sends in request and when response comes back  it will use that method name to call it ...Read further everything will make sense...)

Since all browsers allow injecting java scripts from third party websites without complaining (that they are cross domain) in JSONP the response we need, is wrapped as a Java script method there by fooling the browser to think its as java script.
<script> tag is less restrictive hence in JSONP you got the same JSON response with a call back method added to it. So browser was happy that it was just injecting some java script function and did not complain. Sweet !!!

Enabling JSONP Server side using Servlet as wrapper for JAX-WS webservice
I had an exisitng JAX-WS webservice which returns  JSON response. Most time this webservice is invoked by some other server component. But we had a client who had to call using Ajax and browser started complaining that we are accessing cross domain url.

Let say my webservice url was:

And the caller is on ---> this page has ajax call. (will show later )

So all we did was added a servlet called CalulationServlet which had the URL

package com.rama.test.jsonp;
public class CalculationServlet extends HttpServlet{
   // NOTE: JSONP works only iwth GET request
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);

//JSONP cannot work for POST.....So dont implement. 
  protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

  private void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
     String amount = request.getParameter("amount");
     String rate= request.getParameter("interestRate");
     BigDecimal  principal = new BigDecimal( amount);
     BigDecimal  interestRate = new BigDecimal(rate);        

//If are using Jquery each time the call back method name will be auto generated.// but Parameter name can be controlled
// most often all exmaples I have seen use "callback" as request parameter
//eg: your call method name can be like.  jsonp1337622713385
String callBackJavaScripMethodName = request.getParameter("callback");

//Here called my webservice as if like any other java client.      
//callWebservice -- Takes two input param and returns response as JSON    

 String jsonResponseData =   callWebservice(principal,interestRate);
// so it will look like  
//jsonp1337622713385 ( {"totalInterestPmtAmt":5092.79,"totalPmtAmt":15092.79} );
String jsonPoutput = callBackJavaScripMethodName + "("+ jsonResponseData + ");";

//Write it to Response  

   PrintWriter out = response.getWriter();
NOTE: Its very important that the response content type is set to   text/javascript
Now I edited the web.xml that was already there for my webservice I added the following entry

   <description>This Servlet  was added to support JSONP protocol to resolve cross domain scripting problem
Now my servlet can be invoked using the url  (as the web app name is Calculation)

JQuery to invoke:
Inside the any html page assuming you have Jquery included
<SCRIPT src="scripts/jquery.js"></SCRIPT>


function callWebService() {
///the callback=? the questsion mark will be replace by JQuery with 
//some method name like jsonp1337622713385
//So when response comes back the response is packed inside this method.
//Thats all we did in server side. The callback method name is dynamically 
//generated by JQUERY.

var calcServcURLValue = '';
            url: calcServcURLValue , 
            type: 'get',  /* Dont use post it JSONP doesnt support */
            dataType: 'jsonp',
            success: function(res) {
             alert('Yahoo!!!! We got the Response back')
            error: function(e , msg){ 

function processError(e , msg){
    alert('Call to Service Failed');

//The res object you get is a JSON object 
// Since the JSON response is 
// {"totalInterestPmtAmt":5092.79,"totalPmtAmt":15092.79}
//yes the call back method name will 
//be removed by Jquery isn that neat 

function processResponse(res){
    alert('totalInterestPmtAmt='+ res.totalInterestPmtAmt);
    alert('totalPmtAmt='+ res.totalPmtAmt);


//Add some html and a button to call function callWebService( ) you should be all set.
so this work around will save you from CROSS Domain Issues.


  1. I like the way you write, but please, do somethink for your code, use indent and coloration.

  2. Sure. I will indent. Thanks for the feed back. I tried different templates. I guess I need to find the right CSS.

  3. Thanks, this helped a lot in solving my jsonp problem. great job

  4. Thanks. Hope you did up vote this article on


  5. Hi Ram,

    I want to use the same but in my case has javascrpit which should send message to on redirect from file1 to file2 for user. No server side code available for modifiaction at

    Gaurav Joshi

  6. As described above you may have to think of using
    Option 2 in the above list.

    2. Use some server side re-direct of the request to a servlet or a php script on your own domain which in trun calls third party web site.

  7. Question: Will invoked third party url be able to set cookies? So, JSONP-invoking-client can be recognized if he later invokes third party url?

  8. This comment has been removed by a blog administrator.

  9. I don't get it.. you say it doesn't work for POST, don't implement... then you go and put the code in DoPost ??

    1. Thanks buddy. Copy paste error. I have fixed it.

  10. Good catch. I messed up when naming the methods. Its true we shouldn't add the code into doPost(..) as JSONP will not invoke it.Thanks.

  11. Sorry, but my json is interpreted as string ...any ideas?

  12. Ok I got it, but return object is not in the same order, now is sorted by name. Thank you for your clear example about callback functions

  13. I want to send 2 additional parameters api_key and api_secret to access a particular api. how will request look like. please suggest.

  14. Thanks great to see it all in one spot - good teacher :)

  15. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Java Training in Chennai

  16. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

  17. Nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge so keep on sharing such kind of an interesting blogs.
    jira admin training

  18. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    java training in chennai | java training in bangalore

    java online training | java training in pune

    java training in chennai | java training in bangalore

    java training in tambaram | java training in velachery

  19. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
    python training in chennai | python training in bangalore

    python online training | python training in pune

  20. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    Selenium Training in Chennai | Selenium Training in Bangalore | Selenium Training in Pune

  21. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    rpa training in Chennai

    rpa training in anna nagar | rpa training in marathahalli

    rpa training in btm | rpa training in kalyan nagar

    rpa training in electronic city | rpa training in chennai

    rpa online training | selenium training in training

  22. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Devops Training in pune

  23. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    Best Selenium Training in Chennai | Selenium Training Institute in Chennai | Besant Technologies

    Selenium Training in Bangalore | Best Selenium Training in Bangalore

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

  24. I am really enjoying reading your well-written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
    Hadoop course in Marathahalli Bangalore
    DevOps course in Marathahalli Bangalore
    Blockchain course in Marathahalli Bangalore
    Python course in Marathahalli Bangalore
    Power Bi course in Marathahalli Bangalore

  25. I have read so many articles and definitely this one is the best I have read. Thanks for uploading.
    selenium course
    selenium Testing Training
    Selenium Training in Chennai

  26. emails with the same comment. Is there any way you can remove people from that service? Thanks.
    fire and safety course in chennai