Jaybanuan's Blog

どうせまた調べるハメになることをメモしていくブログ

Tomcat 8でJAX-RS 2.0

はじめに

JAX-RS 2.0のアプリを作成し、Tomcat 8で実行するサンプル。 web.xmlレスの情報が少ないので、まとめておく。 ビルドにはJDK 8とMaven 3を利用。 また、JAX-RS 2.0の実装としてJerseyを利用。 実行にはServlet 3.0に対応したTomcat 7以降(ここで試したのはTomcat 8)が必要。

ディレクトリ構成

.
|-- pom.xml
`-- src
    `-- main
        `-- java
            `-- redj
                `-- hello
                    `-- jersey
                        |-- ApplicationConfig.java
                        `-- GreetingResource.java

ソース

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>redj</groupId>
    <artifactId>hello-jersey</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.22.1</version>
        </dependency>
    </dependencies>
</project>

src/main/java/redj/hello/jersey/GreetingResource.java

package redj.hello.jersey;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("greeting/{name}")
public class GreetingResource {

    @GET
    @Produces("text/plain")
    public String sayHello(@PathParam("name") String name) {
        return "hello," + name + "!";
    }
}

src/main/java/redj/hello/jersey/ApplicationConfig.java

package redj.hello.jersey;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("hello-jersey")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(GreetingResource.class);

        return classes;
    }
}

ビルド

$ mvn clean install

デプロイ

$ cp target/hello-jersey-1.0-SNAPSHOT.war $CATALINA_HOME/webapps/

実行

$ curl http://localhost:8080/hello-jersey-1.0-SNAPSHOT/hello-jersey/greeting/world
hello,world!

参考