如何将 header 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 应用程序的资源类的每个响应添加 header 。但它不添加静态文件的 header 。我还在浏览器和 postman 中检查了文件是否可以访问(但没有 cors header )。我在尝试从 javascript 单页应用程序获取文件时收到错误消息。
最佳答案
以下代码对我有用:
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");
}
}
关于java - 如何将 CORS header 添加到 Jersey 2 中 Grizzly 服务器的 StaticHttpHandler 提供的响应中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58346422/