如何将 CORS 标头添加到 Jersey 2 中灰熊服务器的 StaticHttpHandler 提供的响应?
Posted
技术标签:
【中文标题】如何将 CORS 标头添加到 Jersey 2 中灰熊服务器的 StaticHttpHandler 提供的响应?【英文标题】:How to add CORS header to response served from StaticHttpHandler of Grizzly server in Jersey 2? 【发布时间】:2020-02-09 06:52:40 【问题描述】:如何将标头 CORS(Access-Control-Allow-Origin,Access-Control-Allow-Methods)添加到 Jersey(2.2 版)中由 staticHttpHandler 提供的文件的每个响应文件?
我尝试添加 CorsResponseFilter,但它对静态内容没有帮助。
public static void main(String[] args) throws Exception
String BASE_URI = "http://localhost:8081/";
final ResourceConfig rc = new ResourceConfig().packages("org.example");
rc.register(CorsResponseFilter.class);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
File dir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
StaticHttpHandler staticHttpHandler = new StaticHttpHandler(dir.getPath());
server.getServerConfiguration().addHttpHandler(staticHttpHandler, "/data/");
System.out.println("Press Enter to stop Restful service");
System.in.read();
server.shutdownNow();
这个 CorsResponseFilter 类为来自 Jersey 应用程序的资源类的每个响应添加标头。但它不会为静态文件添加标题。我还检查了浏览器和邮递员是否可以访问文件(但没有 cors 标头)。我在尝试从 javascript 单页应用程序中获取文件时收到错误消息。
【问题讨论】:
【参考方案1】:以下代码适用于我:
public static HttpServer startServer (String base)
final ResourceConfig rc = new ResourceConfig().packages("com.mypackage");
rc.register(MultiPartFeature.class);
rc.register(new CORSFilter());
rc.register(CORSFilter.class);
rc.register(JacksonFeature.class);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(base), rc);
CLStaticHttpHandler staticHandler = new CLStaticHttpHandler(MainServer.class.getClassLoader(), "static/" );
staticHandler.setFileCacheEnabled(false); // change to true in the deploy time
server.getServerConfiguration().addHttpHandler(staticHandler, "/");
CompressionConfig compressionConfig
= server.getListener("grizzly").getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON); // the mode
compressionConfig.setCompressionMinSize(1); // the min amount of bytes to compress
compressionConfig.setCompressableMimeTypes("text/plain", "text/html"); // the mime types to compress
return server;
这是 CORSFilter 类
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
public class CORSFilter implements ContainerResponseFilter
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers", "Content-Type");
【讨论】:
以上是关于如何将 CORS 标头添加到 Jersey 2 中灰熊服务器的 StaticHttpHandler 提供的响应?的主要内容,如果未能解决你的问题,请参考以下文章
Jersey API 中的 multipart/form-data 出现 CORS 错误