[英]Ajax post call to a rest service through servlet
I have a little problem: I'm developing a jQuery Mobile app and i need to make an ajax post call to a rest service. 我有一个小问题:我正在开发jQuery Mobile应用程序,我需要对rest服务进行ajax发布。 I create the pages dynamically using servlets.
我使用servlet动态创建页面。
I tried to make the ajax call to the rest url: 我试图对其余URL进行ajax调用:
http://localhost:8181/myRestServicePath/func?key=value
from a page whit the following url: 在页面上输入以下网址:
http://localhost:8080/Mypage
but i get a cross-orign error from the browser. 但是我从浏览器中收到一个跨源错误。
So i'm tryng to perform this call, passing through a Java servlet using the doPost() method. 因此,我正在尝试执行此调用,并使用doPost()方法通过Java servlet。
Now, my intent is to make an ajax post call from 现在,我的意图是从发出ajax帖子
http://localhost:8080/Mypage
to: 至:
http://localhost:8080/myServletPath/func?key=value
and this servlet should redirect the POST request to my RestService: 并且此servlet应该将POST请求重定向到我的RestService:
http://localhost:8181/myRestServicePath/func?key=value
How can i perform this redirection? 我如何执行此重定向?
There could be several ways to achieve that. 可能有几种方法可以实现这一目标。 I am just sharing 2 commons possibilities as below.
我只分享以下两种常见的可能性。
For POST requests:- You will need to use Apache HTTPClient in your servlet to send the request to web services and get a response. 对于POST请求:-您将需要在servlet中使用Apache HTTPClient将请求发送到Web服务并获得响应。 After getting the response you can send that response to your page.
收到响应后,您可以将该响应发送到您的页面。
For GET Requests:- 对于GET请求:
You don't need extra servlet for cross domain request. 对于跨域请求,您不需要额外的servlet。 You can use JSONP
您可以使用JSONP
jQuery example: jQuery示例:
$.ajax({
url:"http://localhost:8080/myServletPath/func?key=value",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
},
});
For back end example visit Java J2EE Tutorial for Cross Domain JSONP 有关后端示例,请访问Java J2EE跨域JSONP教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.