Serializing URIs
Juneau serializers turn relative URIs into absolute form, using the authority, context root, servlet path and path info of the current request.
When to use it
Use this when your beans or return values contain URI properties that hold relative values (such as servlet:/foo) and clients need fully-qualified links, for example when the resource sits behind a proxy with a different host or context root.
Example
The following serializer resolves six URIs against http://foo.com:123, the context root /myContext, the servlet path /myServlet and the path info /myPath.
import java.net.URI;
import java.util.*;
import org.apache.juneau.marshall.*;
import org.apache.juneau.marshall.json.*;
public class UriExample {
public static void main(String[] args) throws Exception {
var uris = new LinkedHashMap<String,URI>();
uris.put("f1a", URI.create("http://www.apache.org/f1a"));
uris.put("f1b", URI.create("/f1b"));
uris.put("f1d", URI.create("f1d"));
uris.put("f2a", URI.create("context:/f2a/x"));
uris.put("f3a", URI.create("servlet:/f3a/x"));
uris.put("f4a", URI.create("request:/f4a/x"));
var serializer = JsonSerializer.create()
.uriContext(UriContext.of("http://foo.com:123", "/myContext", "/myServlet", "/myPath"))
.uriRelativity(UriRelativity.RESOURCE)
.uriResolution(UriResolution.ABSOLUTE)
.build();
System.out.println(serializer.writeToString(uris));
}
}
It prints:
{"f1a":"http://www.apache.org/f1a","f1b":"http://foo.com:123/f1b","f1d":"http://foo.com:123/myContext/myServlet/f1d","f2a":"http://foo.com:123/myContext/f2a/x","f3a":"http://foo.com:123/myContext/myServlet/f3a/x","f4a":"http://foo.com:123/myContext/myServlet/myPath/f4a/x"}
In a REST resource, the same resolution is configured on the @Rest annotation:
@Rest(
uriAuthority="http://foo.com:123",
uriContext="/myContext"
)
class MyResource {
@RestGet
public URI[] getURIs() {
return new URI[] {
URI.create("http://www.apache.org/f1a"),
URI.create("/f1b"),
URI.create("/f1c/x/y"),
URI.create("f1d"),
URI.create("f1e/x/y"),
URI.create(""),
URI.create("context:/f2a/x"),
URI.create("context:/f2b"),
URI.create("context:/"),
URI.create("context:/.."),
URI.create("servlet:/f3a/x"),
URI.create("servlet:/f3b"),
URI.create("servlet:/"),
URI.create("servlet:/.."),
URI.create("request:/f4a/x"),
URI.create("request:/f4b"),
URI.create("request:/"),
URI.create("request:/..")
};
}
}
Options
URIs are resolved by both regular and part serializers. How each form resolves:
| URI form | Resolves against |
|---|---|
http://www.apache.org/f1a | Left as is. |
/f1b | The authority only. |
f1d | The servlet URI, or the request URI when the relativity is PATH_INFO. |
context:/f2a/x | The context root. |
servlet:/f3a/x | The servlet path. |
request:/f4a/x | The request path. |
URI resolution is controlled by the following settings: