ぺーぺーSEのブログ

備忘録・メモ用サイト。

Spring 3でHello World REST (Jersey) +JSON

Spring 3、Jersey、JSONを連携して実行してみる。
まずはHelloWorldを出力するプロジェクトの作成。
下記のコマンドを実行。(Maven 3を使用)
# 2013/08/22に更新

mvn archetype:generate -DgroupId=org.sample
                       -DartifactId=Spring3HelloWorldJerseyJSON
                       -DarchetypeArtifactId=maven-archetype-webapp
                       -Dversion=0.0.1-SNAPSHOT

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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.sample</groupId>
  <artifactId>Spring3HelloWorldJerseyJSON</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Spring3HelloWorldJerseyJSON</name>
  <url>http://maven.apache.org</url>
  
  <properties>
    <!-- Base Settings -->
    <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
    <encoding>UTF-8</encoding>
    <jdk.version>1.7</jdk.version>
    <project.build.sourceEncoding>${encoding}</project.build.sourceEncoding>
    
    <!-- Library version -->
    <org.springframework.version>3.2.4.RELEASE</org.springframework.version>
    <jersey.version>1.17.1</jersey.version>
    <jersey.contribs.version>1.17.1</jersey.contribs.version>
    <junit.version>4.11</junit.version>
  </properties>
  
  <build>
    <finalName>Spring3HelloWorldJerseyJSON</finalName>
  	<plugins>
  	<!-- compiler -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>${jdk.version}</source>
          <target>${jdk.version}</target>
          <encoding>${encoding}</encoding>
        </configuration>
      </plugin>
  	</plugins>
  </build>
  
  <dependencies>
    <!-- SpringFramework -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    
    <!-- Jersey Contribs -->
    <dependency>
      <groupId>com.sun.jersey.contribs</groupId>
      <artifactId>jersey-spring</artifactId>
      <version>${jersey.version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    
    <!-- Jersey -->
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-server</artifactId>
      <version>${jersey.version}</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-core</artifactId>
      <version>${jersey.version}</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-json</artifactId>
      <version>${jersey.version}</version>
    </dependency>
    
    <!-- test -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>

次に以下を作成する。

  • オブジェクトクラス(org.sample.person.bean.Person)
    • JSON対応したオブジェクトクラス。
  • リソースインターフェース(org.sample.person.resource.PersonResource)
    • HTTPリクエストに対する処理を記述クラス。
    • @Pathや@Getアノテーションを使用する。
  • リソースクラス(org.sample.person.resource.impl.PersonResourceImpl)
    • リソースインターフェースの実装クラス。
    • @Componentアノテーションをつけるのを忘れずに。(これをつけるとSpringがコンポーネントスキャン機能により見つけてくれる)
  • applicationContext.xml
  • web.xml



■オブジェクトクラス(org.sample.person.bean.Person)

package org.sample.person.bean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    private Integer id;
    private String name;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}



■リソースインターフェース(org.sample.person.resource.PersonResource)

package org.sample.person.resource;

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

import org.sample.person.bean.Person;

@Path("/person")
public interface PersonResource {

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    public Person[] getPersons();

    @Path("{id}")
    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    public Person getperson(@PathParam("id") Integer id);
}



■リソースクラス(org.sample.person.resource.impl.PersonResourceImpl)

package org.sample.person.resource.impl;

import org.sample.person.bean.Person;
import org.sample.person.resource.PersonResource;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.NotFoundException;

@Component
public class PersonResourceImpl implements PersonResource {

    private static Person[] persons = {
        createPerson(1, "suzuki", "Tokyo"),
        createPerson(2, "satou", "Osaka"),
        createPerson(3, "tanaka", "Naogya") };

    public Person[] getPersons() {
        return persons;
    }

    public Person getperson(Integer id) {
        if (id > persons.length) {
            throw new NotFoundException("No such person.");
        }
        return persons[id - 1];
    }

    private static Person createPerson(Integer id, String name, String address) {
        Person person = new Person();
        person.setId(id);
        person.setName(name);
        person.setAddress(address);
        return person;
    }
}



■applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <context:annotation-config />
  <context:component-scan base-package="org.sample" />

</beans>



■web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>Jersey Spring Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Spring Web Application</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>



以上でサンプル更新完了。
サンプルを起動したHTTP GETメソッドで下記へアクセスする

http://[FQDN]:8080/Spring3HelloWorldJerseyJSON/person

{
  "person":[
    {"address":"Tokyo","id":"1","name":"suzuki"},
    {"address":"Osaka","id":"2","name":"satou"},
    {"address":"Naogya","id":"3","name":"tanaka"}
  ]
}

が返却される。
また、HTTP GETメソッドで下記へアクセスする

http://[FQDN]:8080/Spring3HelloWorldJerseyJSON/person/1

{
  "address":"Tokyo",
  "id":"1",
  "name":"suzuki"
}

が返却される。




参考:http://d.hatena.ne.jp/w650/20110119/1295411262