ChiranjeeviIT ChiranjeeviIT - 8 months ago 105
reST (reStructuredText) Question

RESTful webservice : how to set headers in java to accept XMLHttpRequest allowed by Access-Control-Allow-Origin

I have a RESTful webservice which will return string and it was written in Java (JAX-WS).
My problem is when I send request to that webservice with URL like :


In the console it's giving me the error message below:

XMLHttpRequest cannot load url Origin localhost is not allowed
by Access-Control-Allow-Origin

How can I handle this issue?

Java code:

public Response getMsg() {
String output = "Jersey say : " ;
return Response.status(200).entity(output).build();

Answer Source

Read here about your issue CORS :

Check if this one help you in your getMsg() method:
return Response.ok(output).header("Access-Control-Allow-Origin", "*").build();

If above doesn't work try to add Jersey filter to your service. Create filter class:

package your.package;

public class CORSFilter implements ContainerResponseFilter {

    public ContainerResponse filter(ContainerRequest creq, ContainerResponse cresp) {

        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

        return cresp;

And register later win web.xml with:

<servlet-name>CORS Filter</servlet-name>
    <servlet-name>CORS Filter</servlet-name>

Another solution is to use this code inside your resource to provide OPTIONS for the browser. Put this in the class where you have @GET.

  public Response getOptions() {
    return Response.ok()
      .header("Access-Control-Allow-Origin", "*")
      .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
      .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();

If non of this work, try to exchange the "*" provided for "Access-Control-Allow-Origin" header with your custom domain where you access this resource. I.g. If you call this from http://localhost::8080 use something like this ("Access-Control-Allow-Origin", "http://localhost:8080") instead of asterisk "*".