環境
Netbeans8.1
プロジェクトを作成
mavenで作成
↓
↓
pom.xmlを修正
<dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> </dependencies>
再ビルド
サンプル
SampleRest.java
package com.mycompany.restful01; import javax.ws.rs.ApplicationPath; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Application; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** */ @Path("/MyRest") @ApplicationPath("/resources") public class SampleRest extends Application{ // http://localhost:8080/Restful01/resources/MyRest/hello @GET @Path("/hello") public String say(){ return "hello,world"; } }
※パッケージは必ず指定しないとうまく動作しない感じです
↓
パラメータ指定
SampleRest2.java
package com.mycompany.restful01; import javax.ws.rs.ApplicationPath; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Application; import javax.ws.rs.core.Response; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** */ @Path("/MyRest") @ApplicationPath("/resources") public class SampleRest2 extends Application{ @GET @Path("/echo") public Response message(@QueryParam("message") String msg){ return Response.ok("msg = [" + msg + "]").build(); } }
↓
json/xml
User.java
package com.mycompany.restful01; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private String email; public User(){ } public User(String name, String email) { super(); this.name = name; this.email = email; } }
SampleRest3.java
package com.mycompany.restful01; import javax.ws.rs.ApplicationPath; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; /** */ @Path("/MyRest") @ApplicationPath("/resources") public class SampleRest3 extends Application{ @GET @Path("/user.xml") @Produces({MediaType.APPLICATION_XML}) public User getUserXml(){ return new User("hoge", "hoge1@test.com"); } @GET @Path("/user.json") @Produces({MediaType.APPLICATION_JSON}) public User getUserJson(){ return new User("hoge", "hoge1@test.com"); } }
↓
所感
結果を返すだけなら意外と簡単な感じ。
CDIなどを使っていないのでなんとも言えないが他の機能と同関連できるか調査することも必要