sebastiandaschner blog

Create links to JAX-RS resources

#jaxrs 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.

public class TestsResource {

    UriInfo uriInfo;

    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, "getTest")

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

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

    .path(TestsResource.class, "getTest")

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: