Java Reference
In-Depth Information
is now annotated with @Produces(MediaType.APPLICATION _ JSON) ; this specii es the
MIME type that this method can produce and returns to the client. The javax.json.Json
and javax.json.JsonArrayBuilder classes are used to build the JSON and wrap it as a
javax.ws.rs.core.Response object before returning it to the client. If all goes well, you should
see the following output in the browser:
[
{"id":123456,"firstname":"Alex","lastname":"Theedom"},
{"id":456789,"firstname":"Murat","lastname":"Yener"}
]
So far, you have seen how to retrieve a resource representation of all users in the system, but what if
you only want one user and you know the user's identii cation number? Well, this is just as simple.
In the URI, you pass the user's ID number like so:
GET /users/123456
and in the REST controller class, you recuperate the ID number by referencing the REST path and
using a URI variable to pass the ID to the method. You annotate the method that will consume
the RESTful API call with @Path("/{id}") , and in the signature of the method, you annotate the
argument to which the ID value should be passed.
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(@PathParam("id") String id){
User user = this.findUser(id);
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
jsonArrayBuilder.add(
Json.createObjectBuilder()
.add("id", user.getId())
.add("firstname", user.getFirstname())
.add("lastname", user.getLastname())
);
return Response.ok(jsonArrayBuilder.build()).build();
}
public User findUser(String id){
return new User("123456", "Alex","Theedom");
}
As you can see in the previous code snippet, the ID string parameter is annotated with
@PathParam("id") so that the ID recuperated from the URI by the @Path("/{id}") annotation
is passed into the method. It is not necessary to include the full path of the URI in the @Path
annotation because the base URI is set in the @Path annotation on the class. All paths set on
methods are relative to the base path set on the class.
The URI variable can be a regular expression. For example, the path annotation
@Path("/{id: [0‐9]*}") will match only IDs that are numbers. Any IDs that don't match will result
in a 404 HTTP response being returned to the client.
Search WWH ::




Custom Search