为了在基于 Jersey 的 JAX-RS 应用程序中促进跨源资源共享 (CORS),您需要实现 ContainerResponseFilter。以下是 Jersey 版本 1.x 和 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"); } }
在 ResourceConfig 中注册此过滤器或通过 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; } }
通过 web.xml 或配置此过滤器ResourceConfig。
注意: 确保有选择地将过滤器应用于所需的资源,以避免暴露敏感信息。
以上是如何在 Jersey JAX-RS 应用程序中实施 CORS?的详细内容。更多信息请关注PHP中文网其他相关文章!