sebastiandaschner blog


Create links to JAX-RS resources

wednesday, january 27, 2016

When creating Hypermedia driven web services you sooner or later need to create URLs to related resources. In JAX-RS there is a helpful functionality to programatically create links to JAX-RS resources.

The UriInfo class can be injected by using @Context — either at the resource method or at the class itself — and used to create links using information from your JAX-RS project.

@Stateless
@Path("tests")
public class TestsResource {

    @Context
    UriInfo uriInfo;

    @Path("{id}")
    public JsonObject getTest(@PathParam("id") String id) {

        // will create the URI pointing to /tests/foobar
        // useful to cross-reference to other resource classes / methods
        URI foobarUri = uriInfo.getBaseUriBuilder()
            .path(TestsResource.class)
            .path(TestsResource.class, "getTest")
            .build("foobar");

        return Json.createObjectBuilder().add("_links", ...);
    }
}

If the UriInfo object is not available the UriBuilder can also be used directly:

UriBuilder.fromResource(TestsResource.class)
    .path(TestsResource.class, "getTest")
    .build("foobar");

Have a look at the JavaDocs of UriInfo and UriBuilder.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: