Home >Java >javaTutorial >How to Implement CORS Handling in JAX-RS with Jersey?
CORS Handling in JAX-RS with Jersey
Introduction
Cross-Origin Resource Sharing (CORS) enables secure communication between a web application and resources hosted on a different domain. Handling CORS is essential in RESTful APIs to allow cross-domain requests. JAX-RS provides a convenient mechanism for handling CORS using custom filters.
Filter Implementation for Jersey 2.x
In Jersey 2.x, a ContainerResponseFilter can be used to add CORS headers to responses. The following filter adds the necessary headers:
import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.core.MultivaluedMap; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { MultivaluedMap<String, String> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); } }
Registering the Filter
The CORS filter can be registered in ResourceConfig as follows:
final ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig.register(CORSFilter.class);
Filter Implementation for Jersey 1.x
For Jersey 1.x, a ContainerResponseFilter can be used as well:
import com.sun.jersey.spi.container.ContainerResponseFilter; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerRequestContext; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public ContainerResponse filter(ContainerRequestContext requestContext, ContainerResponse response) { response.getHttpHeaders().add("Access-Control-Allow-Origin", "*"); response.getHttpHeaders().add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); return response; } }
Web.xml Configuration for Jersey 1.x
In web.xml, configure the filter as follows:
<init-param> <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name> <param-value>com.yourpackage.CORSFilter</param-value> </init-param>
The above is the detailed content of How to Implement CORS Handling in JAX-RS with Jersey?. For more information, please follow other related articles on the PHP Chinese website!