Java でシンプル RESTful サンプル

今風に Java でシンプルな RESTful を作成する方法を調べてみました。さしあたり Jersey を用いて確認しました。

jar ファイル類

以下の組み合わせで動作確認しました。

  • Java 1.8.0_102
  • jaxrs-ri-2.25.zip (api / lib / ext 全て必要)
  • jersey-container-jdk-http-2.25.jar (JdkHttpServerFactory のために必要)

シンプルソースコード

import java.net.URI;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

public class Main {
	public static void main(final String[] args) {
		final URI uri = UriBuilder.fromUri("http://localhost/").port(8080).build();
		final ResourceConfig config = new ResourceConfig();
		config.register(Hello.class);

		JdkHttpServerFactory.createHttpServer(uri, config);

		for (;;) {
			System.out.print('.');
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
			}
		}
	}

	// http://localhost:8080/hello?name=Igaiga
	@Path("/")
	public static class Hello {
		@GET
		@Path("hello")
		@Produces(MediaType.TEXT_PLAIN)
		public String hello(@QueryParam("name") String name) {
			return "Hello '" + name + "' san.";
		}
	}
}

参考にした記事