JAX-RS プロジェクトの作成

REST サービスの関連資産

jaxrs-07.png

ApplicationConfig?.java

リソースファイル

D3Bean.java (HTTP RESPONSE に載せる JSON にマッピングする Bean)

package com.example.jaxrsexam;

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "d3")
public class D3Bean {
    
    private Date date;
    private int freq;    

    public D3Bean() {
        super();
    }
    
    public D3Bean(Date date, int freq) {
        this();
        this.date = date;
        this.freq = freq;
    }

    
    @XmlElement
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @XmlElement
    public int getFreq() {
        return freq;
    }

    public void setFreq(int freq) {
        this.freq = freq;
    }
}

D3Resource.java (処理)

package com.example.jaxrsexam;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.JSONP;

/**
 * REST Web Service
 *
 * @author atsushi
 */
@Path("d3")
@RequestScoped
public class D3Resource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of D3Resource
     */
    public D3Resource() {
    }

    /**
     * JSONを返す.
     * @return Object
     */
    @GET
    @Path("json")
    @Produces(MediaType.APPLICATION_JSON)
    public List<D3Bean> getJson() throws Exception {
        return createDummyData();        
    }
    
    /**
     * XMLを返す.
     * @return Object
     */
    @GET
    @Path("xml")
    @Produces(MediaType.APPLICATION_XML)
    public List<D3Bean> getXml() throws Exception {
        return createDummyData();        
    }
    
    /**
     * XMLを返す.
     * @return Object
     */
    @GET
    @Path("text")
    @Produces(MediaType.TEXT_PLAIN)
    public String getText() throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder sb = new StringBuilder();
        sb.append("date,freq\n");
        for (D3Bean bean : createDummyData()) {
            sb.append(df.format(bean.getDate()));
            sb.append(",");
            sb.append(bean.getFreq());
            sb.append("\n");
        }
        return sb.toString();
    }
    
    /**
     * JSONPを返す.
     * JSONPを返すときには、MIME Type を application/javascript にする
     * application/json だとダメ
     * @return Object
     */
    @GET
    @Path("jsonp")
    @JSONP(queryParam = "callback")
    @Produces("application/javascript")
    public List<D3Bean> getJsonp() {
        return createDummyData();        
    }
    
    /**
     * エラーを返す.
     * @return Object
     */
    @GET
    @Path("error")
    @Produces(MediaType.TEXT_PLAIN)
    public String getError() throws Exception {
        throw new WebApplicationException(Response.Status.NOT_FOUND);
    }
    
    private List<D3Bean> createDummyData() {
        long current = System.currentTimeMillis();
        
        List<D3Bean> ret = new ArrayList<>();
        for (int cnt = 0; cnt < 10; cnt++) {
            ret.add(new D3Bean(new Date(current + cnt * 86400000L), cnt));
        }
        return ret;
    }
}

実行結果

[~]$ curl http://localhost:8080/JAX-RSExam/webresources/d3/json 
[{"date":1371995770259,"freq":0}, 
{"date":1372082170259,"freq":1}, 
{"date":1372168570259,"freq":2}, 
{"date":1372254970259,"freq":3}, 
{"date":1372341370259,"freq":4}, 
{"date":1372427770259,"freq":5}, 
{"date":1372514170259,"freq":6}, 
{"date":1372600570259,"freq":7}, 
{"date":1372686970259,"freq":8}, 
{"date":1372773370259,"freq":9}] 
 
[~]$ curl http://localhost:8080/JAX-RSExam/webresources/d3/jsonp?callback=jQuery12345678 
jQuery12345678( 
[{"date":1371995774786,"freq":0}, 
{"date":1372082174786,"freq":1}, 
{"date":1372168574786,"freq":2}, 
{"date":1372254974786,"freq":3}, 
{"date":1372341374786,"freq":4}, 
{"date":1372427774786,"freq":5}, 
{"date":1372514174786,"freq":6}, 
{"date":1372600574786,"freq":7}, 
{"date":1372686974786,"freq":8}, 
{"date":1372773374786,"freq":9}]) 
 
[~]$ curl http://localhost:8080/JAX-RSExam/webresources/d3/xml 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<d3Beans> 
<d3><date>2013-06-23T22:56:27.035+09:00</date><freq>0</freq></d3> 
<d3><date>2013-06-24T22:56:27.035+09:00</date><freq>1</freq></d3> 
<d3><date>2013-06-25T22:56:27.035+09:00</date><freq>2</freq></d3> 
<d3><date>2013-06-26T22:56:27.035+09:00</date><freq>3</freq></d3> 
<d3><date>2013-06-27T22:56:27.035+09:00</date><freq>4</freq></d3> 
<d3><date>2013-06-28T22:56:27.035+09:00</date><freq>5</freq></d3> 
<d3><date>2013-06-29T22:56:27.035+09:00</date><freq>6</freq></d3> 
<d3><date>2013-06-30T22:56:27.035+09:00</date><freq>7</freq></d3> 
<d3><date>2013-07-01T22:56:27.035+09:00</date><freq>8</freq></d3> 
<d3><date>2013-07-02T22:56:27.035+09:00</date><freq>9</freq></d3> 
</d3Beans> 
 
[~]$ curl http://localhost:8080/JAX-RSExam/webresources/d3/text 
date,freq
2013-06-23 22:56:31,0 
2013-06-24 22:56:31,1 
2013-06-25 22:56:31,2 
2013-06-26 22:56:31,3 
2013-06-27 22:56:31,4 
2013-06-28 22:56:31,5 
2013-06-29 22:56:31,6 
2013-06-30 22:56:31,7 
2013-07-01 22:56:31,8 
2013-07-02 22:56:31,9 
 
[~]$ curl http://localhost:8080/JAX-RSExam/webresources/d3/error -I 
HTTP/1.1 404 Not Found 
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition  4.0  Java/Oracle Corporation/1.7) 
Server: GlassFish Server Open Source Edition  4.0 
Content-Language: 
Content-Type: text/html 
Date: Sun, 23 Jun 2013 13:56:44 GMT 
Content-Length: 1082 

解説

Class への Annotation

@Path("d3")
@RequestScoped
public class D3Resource {

Method への Annotation

@GET
@Path("json")
@Produces(MediaType.APPLICATION_JSON)
public List<D3Bean> getJson() throws Exception {
  return createDummyData();
}

GET パラメータを受け取る (Query Parameter)

@GET
@Path("order")
public Response order(@QueryParam("item") String item, @QueryParam("amount") int amount) {
  // 注文処理
}

GET URLの一部をパラメータとみなす

@GET
@Path("item/{id}")
public Response order(@PathParam("id") String itemId) {
  // 商品検索処理
}

POST で パラメータを受け取る

@POST
@Path("item")
public Response order(@FormParam("id") String itemId, @FormParam("amount") int amount) {
  // 商品受注処理
}

POST で Bean を受け取る

@POST
@Path("item")
public Response order(@BeanParam OrderBean order) {
  // 商品受注処理
}
 
@Data
public class OrderBean {
  @FormParam("id")
  private String itemId;
  
  @FormParam("amount")
  private int amount;
}

cf. @Data は Lombok

POST で JSON を受け取る

POST で HTTP BODY を受け取る

@POST
@Path("setNewItem/{id}")
@Consumes(MediaType.APPLICATION_XML)
public Response setNewItem(@PathParam("id") String itemId, javax.xml.bind.JAXBElement elem) {
  // 商品登録処理
}
MIME Type (@Consumes)Data Type
*/*byte[]
*/*java.lang.String
*/*java.io.InputStream?
*/*java.io.Reader
*/*java.io.File
*/*javax.activation.DataSource?
text/xml, application/xml, application/-*+xmljavax.xml.transform.Source
text/-xml, application/xml, application/*+xmljavax.xml.bind.JAXBElement
application/x-www-form-urlencodedMultivaluedMap?<String, String>
*/*javax.ws.rs.core.StreamingOutput?

サービスの絶対パスを取得

EJB呼び出し

public class D3Resourc {
  @EJB
  private GeoEJB geoEJB;

HTTP HEADER の取得

public class D3Resourc {
  @GET
  public String doSomething(@Context HttpHeaders headers) {
    // do something
  }
}

Cookie の取得

public class D3Resourc {
  @GET
  public String doSomething(@CookieParam("sessionid") sessionId) {
    // do something
  }
}

ERROR の返却

JAX-RS で HttpServletRequest? を受け取る

メソッド引数に @Context HttpServletRequest? request

JSONP

/**
 * JSONPを返す.
 * JSONPを返すときには、MIME Type を application/javascript にする
 * application/json だとダメ
 * @return Object
 */
@GET
@Path("jsonp")
@JSONP(queryParam = "callback")
@Produces("application/javascript")
public List<D3Bean> getJsonp() {
  return createDummyData();        
}

ファイルダウンロード

    @GET
    @Path("/download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response download() throws UnsupportedEncodingException {
        StringBuilder contents = new StringBuilder();
        contents.append("日本語");
        InputStream is = new ByteArrayInputStream(contents.toString().getBytes("UTF-8"));
        
        String fname = URLEncoder.encode("日本語ファイル名.txt", "UTF-8");
        return Response.ok(is)
                .header("Content-disposition", "attachment; filename=" + fname)
                .build();
    }

ファイルアップロード

Glassfish 3

Glassfish 4

ライフサイクル・セキュリティ

HTTP Error 415 Unsupported media type Explained

@GET
@Path("item")
public Response order(@FormParam("id") final String itemId) {
  // 商品検索処理
}

Java#Glassfish


*1 jersey-server は、ビルド時に参照するだけ。実行環境にはあるので war に入れんといて

添付ファイル: filedl2.png 407件 [詳細] filedl1.png 414件 [詳細] filejaxrs-07.png 421件 [詳細] filejaxrs-06.png 438件 [詳細] filejaxrs-05.png 454件 [詳細] filejaxrs-04.png 425件 [詳細] filejaxrs-03.png 455件 [詳細] filejaxrs-02.png 441件 [詳細] filejaxrs-01.png 460件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2016-02-12 (金) 22:31:19 (294d)
ISBN10
ISBN13
9784061426061