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) { MultivaluedMapheaders = 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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3