RestEasyで簡単REST実装

Maven2で必要なlibを定義して取得します。

次にレスポンスでXMLを使用する場合はアノテーションでBeanに対して
XMLの定義を行ないます。

GET、PUT、POST、DELETE等の処理に応じた実装を行ない
Beanを生成、ステータスコードをセットしてあげるだけで
あとはよしなにRestEasyがやってくれます。

下記のコードの場合、

http://localhost:8080/sample/sample/xx

をGETすると下記のようなXMLが200で返ってくるサンプルになります。

#下記はブラウザで開いてます

<response agent="Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.126 Safari/533.4">
  <input>xx</input>
</response>

Maven2のpom.xml

<?xml version="1.0" encoding="UTF-16"?>
<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>sample</groupId>
  <artifactId>sample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <!-- TODO project name  -->
  <name>quickstart</name>
  <description/>
  <dependencies>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-jaxrs</artifactId>
      <version>2.0.1.GA</version>
      <!-- filter out unwanted jars -->
      <exclusions>
        <exclusion>
          <groupId>commons-httpclient</groupId>
          <artifactId>commons-httpclient</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.xml.bind</groupId>
          <artifactId>jaxb-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.xml.bind</groupId>
          <artifactId>jaxb-impl</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-jettison-provider</artifactId>
      <version>2.0.1.GA</version>
      <exclusions>
        <exclusion>
          <groupId>javax.xml.bind</groupId>
          <artifactId>jaxb-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.xml.bind</groupId>
          <artifactId>jaxb-impl</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.xml.stream</groupId>
          <artifactId>stax-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
  <repositories>
    <repository>
      <id>jboss</id>
      <name>jboss repo</name>
      <url>http://repository.jboss.org/nexus/content/groups/public/</url>
    </repository>
  </repositories>
  <build>
    <resources>
      <resource>
        <filtering>false</filtering>
        <directory>src/main/resources</directory>
      </resource>
      <resource>
        <filtering>false</filtering>
        <directory>src/main/java</directory>
        <includes>
          <include>**</include>
        </includes>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <filtering>false</filtering>
        <directory>src/test/java</directory>
        <includes>
          <include>**</include>
        </includes>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <inherited>true</inherited>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
          <optimize>true</optimize>
          <debug>true</debug>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>
          <downloadSources>true</downloadSources>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
     version="2.4">

    <display-name>sample</display-name>

    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <listener>
        <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>

    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

XMLを生成する為のBean

package sample.sample.bean;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="response")
public class ResponseBean {
	
	@XmlAttribute(name="agent")
	public String userAgent;
	
	@XmlElement(name="input")
	public String inputString;

}

GETメソッドを処理してレスポンスを返す処理

package sample.sample.resources;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import sample.sample.bean.ResponseBean;

/**
 * /sampleに対するリソース
 * 
 * @author bose999
 *
 */
@Path("/sample")
public class SampleResource {
	
	/**
	 * コンストラクタ
	 */
	public SampleResource(){
	}
	
	/**
	 * /コンテキストルート/sample/xxxx
	 * という形式のURLでGETコールされた場合の処理
	 * 
	 * @param userAgent HTTPプロトコルヘッダーのUser-Agent
	 * @param inputString URLに定義した引数
	 * @return Response
	 */
	@GET // GETメソッドに対応
	@Path("/{inputString}") // /コンテキスト名/sample/xxxx という形式のURLでxxxをパラメータとして定義
	@Produces("application/xml") // xmlを返すように定義 jsonもここを変えるだけ
	public Response getSample(@HeaderParam("User-Agent") String userAgent, @PathParam("inputString") String inputString){
		
		// XMLを生成
		ResponseBean responseBean = new ResponseBean();
		responseBean.userAgent = userAgent;
		responseBean.inputString = inputString;
		
		// Responseを生成するResponseBuilderをステータスコード200で生成
		ResponseBuilder responseBuilder = Response.status(200);
		
		// XMLを返す為にResponseBeanを渡す
		responseBuilder = responseBuilder.entity(responseBean);
		
		// Responseを生成する
		Response response = responseBuilder.build();	
		
		// RestEasyにステータスコード200でResponseBeanの内容でXMLを生成して処理を返してもらう
		return response;
	}
}