Java 通过servlet对rest服务的Ajax post调用

Java 通过servlet对rest服务的Ajax post调用,java,jquery,ajax,rest,servlets,Java,Jquery,Ajax,Rest,Servlets,我有一个小问题: 我正在开发一个jQuery移动应用程序,我需要对rest服务进行ajax post调用。 我使用servlet动态创建页面 我尝试对rest url进行ajax调用: http://localhost:8181/myRestServicePath/func?key=value 从包含以下url的页面: http://localhost:8080/Mypage 但是我从浏览器中得到了一个交叉源错误 所以我尝试执行这个调用,使用doPost()方法通过一个Javaservlet

我有一个小问题: 我正在开发一个jQuery移动应用程序,我需要对rest服务进行ajax post调用。 我使用servlet动态创建页面

我尝试对rest url进行ajax调用:

http://localhost:8181/myRestServicePath/func?key=value
从包含以下url的页面:

http://localhost:8080/Mypage
但是我从浏览器中得到了一个交叉源错误

所以我尝试执行这个调用,使用doPost()方法通过一个Javaservlet

现在,我的意图是从

 http://localhost:8080/Mypage
致:

这个servlet应该将POST请求重定向到我的RestService:

http://localhost:8181/myRestServicePath/func?key=value

如何执行此重定向?

有几种方法可以实现此目的。我只是分享两个共同的可能性如下

对于POST请求:- 您需要在servlet中使用ApacheHttpClient将请求发送到web服务并获得响应。收到响应后,您可以将该响应发送到页面

对于GET请求:-

跨域请求不需要额外的servlet。你可以用

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");
     },
});
$.ajax({
url:“http://localhost:8080/myServletPath/func?key=value",

dataType:'jsonp',//注意!jsonp也许您应该考虑将rest服务和其他Servlet保持在同一端口上?这将是典型的配置,解决了您的困难。@MalcolmSmith我无法在同一端口上同时注册Servlet和rest服务。我不想使用jsonp,我需要使用json。Servlet将发送response as response.setContentType(“text/javascript”);对于Visit的详细信息,这将是一个JSON响应,您不必担心任何事情。只需发送回调方法名称。即使您没有指定回调方法名称,jQuery也会为您处理:)@JaffarRamay我的rest方法是用来解析一个URL的,就像我在问题中写的一样,而且最重要的是,jsonp不支持POST。@JaffarRamay是的,谢谢。我正在了解有关Apache HTTPClient的信息。
$.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");
     },
});