Home >Java >javaTutorial >How to Implement CORS in a Jersey JAX-RS Application?
To facilitate Cross-Origin Resource Sharing (CORS) in your Jersey-based JAX-RS application, you'll need to implement a ContainerResponseFilter. Here's the appropriate implementation for Jersey versions 1.x and 2.x:
import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.HttpHeaders; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { response.getHeaders().add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.getHeaders().add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "CSRF-Token, X-Requested-By, Authorization, Content-Type"); response.getHeaders().add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); response.getHeaders().add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS, HEAD"); } }
Register this filter in your ResourceConfig or manually via web.xml.
import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { response.getHttpHeaders().add("Access-Control-Allow-Origin", "*"); response.getHttpHeaders().add("Access-Control-Allow-Headers", "CSRF-Token, X-Requested-By, Authorization, Content-Type"); response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); return response; } }
Configure this filter via web.xml or ResourceConfig.
Note: Ensure the filter is applied selectively to the desired resources to avoid exposing sensitive information.
The above is the detailed content of How to Implement CORS in a Jersey JAX-RS Application?. For more information, please follow other related articles on the PHP Chinese website!