Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 354
stocked Avatar asked Apr 27 '12 02:04

stocked


2 Answers

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.

like image 127
Hank Avatar answered Dec 05 '22 12:12

Hank


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

Create new in project

and select Cross-Origin Resource Sharing Filter

Create new Cross-origin filter

like image 32
Leonardo Mora Avatar answered Dec 05 '22 13:12

Leonardo Mora