Our Work

Enable CORS for JAVA API for RESTful Web Services (JAX-RS) in Liferay 7.X

Updated today

To enable cross domain access for JAX-RS services, we need to create filter which implements ContainerResponseFilter and then we also need to add ContainerResponseFilter object to the resourceconfig.

For the Starters JAX-RS: Java API for RESTful Web Services (JAX-RS) is a Java programming language API spec that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern.[1] JAX-RS uses annotations, introduced in Java SE 5, to simplify the development and deployment of web service clients and endpoints.

The following code snippet below gives us how to achieve this.

  • Step 1 : Create a class which implements ContainerResponseFilter, which contains

@Provider
@PreMatching
public class CorsFilter implements ContainerResponseFilter {
    private Log logger = LogFactoryUtil.getLog(getClass());
    @Override
    public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext cres)
   throws IOException {
   logger.info("Writing CORS headers");
   cres.getHeaders().add("Access-Control-Allow-Origin", "*"); // Update specific domains instead of giving to all
   cres.getHeaders().add("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,Authorization,content-type");
   cres.getHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,HEAD");
   cres.getHeaders().add("Access-Control-Max-Age", "1209500");
    }
}
  • Step 2: We need to add object of ContainerResponseFilter to resource config as below


@ApplicationPath("/org")
@Component(immediate = true, service = Application.class)
public class MclRestServiceApplication extends Application {
    @Override
    public Set<Object> getSingletons() {
   final Set<Object> singletons = new HashSet<>();
    	singletons.add(this);
// Giving cors filter object to the application/resource config
    	singletons.add(new CorsFilter());
    	return singletons;
    }
}
  • Step 3:  Our module needs to be deployed to reflect the changes

Looking for Liferay Developer?

KTree is the best offshore Liferay development company with extensive experience in Liferay Portal Development services along with Upgrade & Migration. Hire Liferay developers or Liferay development services from LiferayDeveloper.

Request For Quote