---
title: JAX-RS 2.0をスタンドアローンで使う
tags: []
categories: ["Programming", "Java", "JAX-RS", "2.0"]
date: 2013-10-28T02:00:39Z
updated: 2013-10-28T02:00:39Z
---

JAX-RS 2.0というかJerseyをスタンドアローンで使う(Servletは使わない)ためのメモ。
サーバーにはGirzzlyを使用する。

### pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>restapi</groupId>
        <artifactId>standalone-jaxrs-sample</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey.core</groupId>
                <artifactId>jersey-server</artifactId>
                <version>2.0</version>
            </dependency>
            <dependency>
                <groupId>org.glassfish.jersey.containers</groupId>
                <artifactId>jersey-container-grizzly2-http</artifactId>
                <version>2.0</version>
            </dependency>
        </dependencies>
    </project>

### エントリポイント

    import java.io.IOException;
    import java.net.URI;
    
    import org.glassfish.grizzly.http.server.HttpServer;
    import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
    import org.glassfish.jersey.server.ResourceConfig;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
            HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI
                    .create("http://localhost:8080/"), new ResourceConfig()
                    .packages("api"));
            System.out.println("==== Enter key to stop server ====");
            System.in.read();
            server.stop();
        }
    
    }

### リソースサンプル

    package api;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    @Path("hello")
    public class HelloResource {
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String hello() {
            return "hello world!";
        }
    }

`Main`を実行して、http://localhost:8080/helloにアクセスすれば「Hello World!」が表示される

localhost:8080/application.wadlでリソース一覧が表示される


次はCDI連携を試す。
JerseyにはJSR-330実装のHK2が同梱されているので、このままでもDIは使えるのだが・・
