Java Reference
In-Depth Information
@GET
public Response doGet(@QueryParam("user") String user) {
System.out.println("In Old doGet.");
URI uri = UriBuilder.fromUri(REDIR_PATH).
path("{a}").
queryParam("user", "{value}").
build(REDIR_SERVICE, user);
Response response = Response.temporaryRedirect(uri).build();
System.out.println("Redirecting to " + uri);
return response;
}
}
The simplest new part of this code is that you just have your method return a
Response
in-
stance, and build that response using the factory method based on the HTTP status you want to
send. In this case, you want to redirect, so you'll use the
temporaryRedirect
method (there
are others for
ok
,
noContent
,
serverError
, and so forth). Once you have the URI instance
representing where you want to redirect to, it's easy. You just pass that to the response and call
build
.
NOTE
This class expects these query parameters, so if you don't pass them, your client will see a 500 server
error indicating that the necessary values to build the template don't exist.
The tricky part of this code is the URI. This class is part of the REST core, and follows
the Gang of Four Builder pattern. Like with
StringBuilder
, each method invocation on
UriBuilder
returns the newly modified object, allowing you to make further modifications.
Here's the basic idea:
1. Create the initial URI object by passing it the base path of the service you want to
redirect to. At this point, you have a URI of
http://localhost:8080/restexamples/
resources/
.
2. Use the
path
method to create a new instance of the
UriBuilder
that uses the template
notation (here,
{a}
) to append the service name once you call build.