Dragos
Dragos

Reputation: 81

JQuery post to a Tomcat Servlet

I am trying to make a JQuery $.post to a Java Servlet. I integrated the Tomcat server into Apache and if the Tomcat server is on the same machine as the Apache the $.post succeded. (The Java Servlet receives it).

If the Tomcat servlet is on a remote machine and if I make $.post(http://ip:8080/App/MyServlet,...) the servlet doesn't receive anything.

If I make a JQuery $.post on my machine I have like this $.post(Myservlet,.....). If I try like this : $.post(http://localhost:8080/App/MyServlet,...) it doesn't work.

How should I make a JQuery $.post to a remote uri?

How should the remote uri for a Tomcat Servlet look like?

Thanks,

Upvotes: 0

Views: 1535

Answers (1)

Anthony
Anthony

Reputation: 37075

Jquery runs in the browser (client-side), which means it's subject to the browser's same-origin policy, which is a good thing.

This means ajax requests that are GET or POST can only be made to the domain of the page making the ajax request.

There are 2 ways to bypass the policy. The first is to have the remote server vouch for the request, the second is to sneak around the browser's same-origin policy.

So if you have control over the remote server, or if the admin who does takes requests to open the server/domain to foriegn ajax requests, then the server just needs to send the following header:

Access-Control-Allow-Origin: your-local-domain.org

The browser gets back the response header, sees that the requesting page is in the above list, and allows the response through.

If you have no control over the remote server, here are the sneakier ways to get around same-origin policy:

  1. Make an ajax request to a local url with the parameters, and have it pass it along to the servlet, and the have that proxy script return whatever the servlet responds with.

  2. JSONP (which I'm still fuzzy on, honestly, but jquery's ajax documentation goes into it)

  3. Script injection, where you leverage the fact that the script element's src is not limited by the same-origin policy.

Of the 3, I think the first is the safest, least hackish, and most honest (so to speak), but JSONP has become the simple and easy way to pull of a cross-domain request in jquery.

Upvotes: 2

Related Questions