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: *
Access-Control-Allow-Origin: http://test.com:8080 http://foobar.com
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: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)

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:
http://abcd.com/Calculation/CalculationWebServiceImpl.wsdl

And the caller is on
http://xyz.com/displayRate.html ---> this page has ajax call. (will show later )

So all we did was added a servlet called CalulationServlet which had the URL
http://abcd.com/Calculation/CalculationServlet

//SERVLET:
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  

   response.setContentType("text/javascript");
   PrintWriter out = response.getWriter();
   out.println(jsonPoutput);
 }    
}
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

  <servlet>
   <description>This Servlet  was added to support JSONP protocol to resolve cross domain scripting problem
    </description>
        <display-name>CalculationServlet</display-name>
       <servlet-name>CalculationServlet</servlet-name>
        <servlet-class>com.rama.test.jsonp.CalculationServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CalculationServlet</servlet-name>
       <url-pattern>/CalculationServlet</url-pattern>
    </servlet-mapping>
Now my servlet can be invoked using the url
http://abcd.com/Calculation/CalculationServlet?amount=10000  (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>

<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 = 'http://abcd.com/Calculation/CalculationServlet?amount=10000&callback=?';
    $.ajax({ 
            url: calcServcURLValue , 
            type: 'get',  /* Dont use post it JSONP doesnt support */
            dataType: 'jsonp',
            success: function(res) {
             alert('Yahoo!!!! We got the Response back')
             processResponse(res);
          }
          , 
            error: function(e , msg){ 
                processError(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);
}

</script>

//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.

104 comments:

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

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

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

    ReplyDelete
  4. Thanks. Hope you did up vote this article on stackoverflow.com

    -Ram

    ReplyDelete
  5. Hi Ram,

    I want to use the same but in my case www.TO.com/file.jsp has javascrpit which should send message to WWW.FROM.com/file2.jsp on redirect from file1 to file2 for user. No server side code available for modifiaction at FROM.com.

    Regards,
    Gaurav Joshi

    ReplyDelete
  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.

    ReplyDelete
  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?

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

    ReplyDelete
  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 ??

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

      Delete
  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.

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

    ReplyDelete
  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

    ReplyDelete
  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.

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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
    FITA
    Selenium Training in Chennai

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

    ReplyDelete
  27. We are a group of volunteers and starting a new initiative in a community. Your blog provided us valuable information to work on.You have done a marvellous job!
    Java training in Chennai

    Java training in Bangalore

    ReplyDelete
  28. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    Selenium training in Chennai

    ReplyDelete
  29. You have worked to perfection on this article. Thanks for taking the time to post search valuable information. I Recommendation this. JSON Formatter Online

    ReplyDelete
  30. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Thanks & Regards,
    VRIT Professionals,
    No.1 Leading Web Designing Training Institute In Chennai.

    And also those who are looking for
    Web Designing Training Institute in Chennai
    SEO Training Institute in Chennai
    Photoshop Training Institute in Chennai
    PHP & Mysql Training Institute in Chennai
    Android Training Institute in Chennai

    ReplyDelete
  31. Nice tips. Very innovative... Your post shows all your effort and great experience towards your work Your Information is Great if mastered very well.
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  32. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information regarding Microsoft Azure which is latest and newest,

    Regards,
    Ramya

    Azure Training in Chennai
    Azure Training Center in Chennai
    Best Azure Training in Chennai
    Azure Devops Training in Chenna
    Azure Training Institute in Chennai
    Azure Training in Chennai OMR
    Azure Training in Chennai Velachery
    Azure Online Training
    Azure Training in Chennai Credo Systemz
    DevOps Training in Chennai Credo Systemz

    ReplyDelete
  33. And indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
    SOFTWARE TRAINING IN CHENNAI
    POWERBI TRAINING IN CHENNAI
    CCNA TRAINING IN CHENNAI
    ANDROID TRAINING IN CHENNAI

    ReplyDelete
  34. It's a Very informative blog and useful article thank you for sharing with us, keep posting learn more about BI Tools Thanks for sharing valuable information. Your blogs were helpful to tableau learners. I request to update the blog through step-by-step. Also, find Technology news at
    Tableau Training

    Android Online Training

    Data Science Certification

    Dot net Training in bangalore

    Blog.

    ReplyDelete
  35. very informative blog and useful article thank you for sharing with us , keep posting learn more about aws with cloud computing AWS Online Training

    ReplyDelete
  36. An astounding web diary I visit this blog, it's inconceivably magnificent. Strangely, in this current blog's substance made point of fact and sensible. The substance of information is instructive.
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  37. A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  38. A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  39. A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  40. Appericated the efforts you put in the content of DevOps .The Content provided by you for DevOps is up to date and its explained in very detailed for DevOps like even beginers can able to catch.Requesting you to please keep updating the content on regular basis so the peoples who follwing this content for DevOps can easily gets the updated data.
    Thanks and regards,
    DevOps training in Chennai
    DevOps course in chennai with placement
    DevOps certification in chennai
    DevOps course in Omr

    ReplyDelete
  41. A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  42. A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  43. Great stuff, Great post i must say thanks for the information.

    ExcelR Data Science Course Bangalore

    ReplyDelete
  44. I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.
    data analytics certification courses in Bangalore
    ExcelR Data science courses in Bangalore

    ReplyDelete
  45. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete
  46. An astounding web diary I visit this blog, it's inconceivably magnificent. Strangely, in this current blog's substance made point of fact and sensible. The substance of information is instructive.
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  47. I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more.

    Data Science Course

    ReplyDelete
  48. Gangaur Realtech is a professionally managed organisation specializing in real estate services where integrated services are provided by professionals to its clients seeking increased value by owning, occupying or investing in real estate.data science course in dubai

    ReplyDelete
  49. I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more.data science course in dubai

    ReplyDelete
  50. A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  51. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!data science course in dubai

    ReplyDelete
  52. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!data science course in dubai

    ReplyDelete
  53. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.data science course in dubai

    ReplyDelete
  54. A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  55. I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.data science course in dubai

    ReplyDelete
  56. I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.data science course in dubai

    ReplyDelete
  57. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!
    machine learning course in bangalore

    ReplyDelete
  58. Thanks for a nice share you have given to us with such an large collection of information.
    Great work you have done by sharing them to all. for more info
    simply superb.PGDCA class in bhopal
    autocad in bhopal
    3ds max classes in bhopal
    CPCT Coaching in Bhopal
    java coaching in bhopal
    Autocad classes in bhopal
    Catia coaching in bhopal

    ReplyDelete
  59. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    machine learning course bangalore

    ReplyDelete
  60. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading Python classes in pune new articles. Keep up the good work!

    ReplyDelete
  61. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!
    www.technewworld.in
    How to Start A blog 2019
    Eid AL ADHA

    ReplyDelete
  62. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.

    blue prism training in chennai | blue prism course in chennai | best blue prism training institute in chennai | blue prism course in chennai | blue prism automation in chennai | blue prism certification in chennai

    ReplyDelete
  63. This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this,
    Great website

    ReplyDelete
  64. Excellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I’ll be waiting for your next post. Thanks .Keep it up! Kindly visit us @Luxury Boxes
    Premium Packaging
    Luxury Candles Box
    Earphone Packaging Box
    Wireless Headphone Box
    Innovative Packaging Boxes
    Wedding gift box
    Leather Bag Packaging Box
    Cosmetics Packaging Box
    Luxury Chocolate Boxes

    ReplyDelete
  65. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    data analytics course malaysia

    ReplyDelete
  66. This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this..
    data analytics course malaysia

    ReplyDelete
  67. An overwhelming web journal I visit this blog, it's unfathomably amazing. Unusually, in this present blog's substance made inspiration driving truth and reasonable. The substance of data is enlightening
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete