ProductResource クラスに次のメソッドを追加する。
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getProduct(@PathParam("id") int id) {
IDAOMock dao = DAOMock.getInstance();
try {
Product product = dao.select(id);
return Response.ok(product).build();
} catch (Exception e) {
e.printStackTrace();
// statusに4xxや5xxを設定してリクエストに対してHTTPのプロトコルを使い、
// サーバの処理状態(リクエスト不正やサーバ処理エラーなど)を通知することができる
int status = 400;
return Response.status(status).build();
}
}
javado.lec06.Main を実行しなおす。
Rest Client で、http://localhost:8080/myapp/product/2 を開くと下のようなJSONが、
{"id":2,"name":"孤独のグルメ2","price":994}
http://localhost:8080/myapp/product/3 を開くと、 400: Bad Request
が表示されればOK。
--