Q:

GlassFish: How to set Access-Control-Allow-Origin header

I am using the latest version of GlassFish.  I want to set the Access-Control-Allow-Origin header in response so that my API which is hosted on GlassFish can be called from any domain.  But I am not able to find out where to set it. 

A:

In my case, the API requests are exclusively handled by Jersey, therefore I can set response headers in a ContainerResponseFilter:
package my.app;

import com.sun.jersey.spi.container. ContainerRequest;
import com.sun.jersey.spi.container. ContainerResponse;
import com.sun.jersey.spi.container. ContainerResponseFilter;

public class CrossOriginResourceSharingFilter implements ContainerResponseFilter {

    @Override
    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");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept");

        return cresp;
    }
}

The filter gets enabled in web.xml:
<servlet>
    <servlet-name>Gateway Servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet. ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.spi.container. ContainerResponseFilters</param-name>
        <param-value>my.app. CrossOriginResourceSharingFilter</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

If you don't use Jersey, I guess you can create a similar servlet response filter. 

A:

The best and easiest way of doing this, is right click on the project

and select Cross-Origin Resource Sharing Filter

