Handling CORS with JAX-RS Using Jersey
Problem: You're encountering a CORS issue while handling requests with JAX-RS and Jersey. Specifically, the server is not setting the necessary CORS headers, leading to the error "No 'Access-Control-Allow-Origin' header is present on the requested resource."
Solution: To handle CORS in JAX-RS with Jersey, you need to implement a ContainerResponseFilter. The difference in implementation depends on whether you're using Jersey 1.x or 2.x.
Jersey 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.MultivaluedMap; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Headers", "CSRF-Token, X-Requested-By, Authorization, Content-Type"); headers.add("Access-Control-Allow-Credentials", "true"); headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); } }
Jersey 1.x:
import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public ContainerResponse filter(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; } }
Additional Notes:
The above is the detailed content of How to Solve CORS Issues in JAX-RS with Jersey?. For more information, please follow other related articles on the PHP Chinese website!