LoginSignup
3
3

More than 5 years have passed since last update.

Jersey+JdkHttpServerでCORS対応の軽量RESTサーバを立てる

Last updated at Posted at 2016-03-31

RESTの軽量サーバを立てたい

Jerseyを使っていて、手元で軽量なRESTサーバを立てたければ、JdkHttpServer を使用するのは良い選択肢です。しかし、Webアプリケーションはnode.jsで書いていて、RESTはJavaで書いているなどという場合には、HTTPレスポンスにAccess-Control-Allow-Originヘッダがないと、CORS(Cross-Origin Resource Sharing)対応じゃないからダメだよ、とブラウザに怒られてしまいます。

意外とJdkHttpServerを使用したシンプルなサンプルコードがなかったので、とても簡単なものですが以下に載せておきます。フィルタをResourceConfigに登録すればOKです。

RestServer.java
package rest.server;

import java.io.IOException;
import java.net.URI;

import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import com.sun.net.httpserver.HttpServer;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;

public class RestServer {

    public static class CORSFilter implements ContainerResponseFilter {
        @Override
        public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
            response.getHeaders().add("Access-Control-Allow-Origin", "*");
        }
    }   
    public static void main(String[] args) throws IOException {
        URI uri = URI.create("http://localhost:8080/api/");
        ResourceConfig rc = new ResourceConfig();
        rc.register(CORSFilter.class);
        rc.packages("rest.services");
        final HttpServer httpServer = JdkHttpServerFactory.createHttpServer(uri, rc);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> httpServer.stop(0)));
    }
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3