Can anyone suggest me which is the best approach to redirect an URL using REST among the below two ways:
1. httpResponse.sendRedirect("URL");
2. Response.temporaryRedirect(new URI("path"));
Can anyone suggest me which is the best approach to redirect an URL using REST among the below two ways:
1. httpResponse.sendRedirect("URL");
2. Response.temporaryRedirect(new URI("path"));
There are many forms of redirect. The
3xx
family of HTTP status codes contains:301 Moved Permanently
307 Temporary Redirect
These and the other codes have different semantic. Which is right depends on your situation. Have the resources been permanently been moved to a new location? Or is the redirect only temporary?
There are several types of redirects
According to the RFC 7231, the current reference for the semantics and content of the HTTP/1.1, there are several types of redirects. They are all
The correct one depend on your needs. However, these are the most commons:
Performing the redirects in JAX-RS
By the code you posted in the question, I believe you are using the JAX-RS API. If so, you can perform the redirects as following:
For more details, the
Response
class documentation may be useful.Other details that can be useful when using JAX-RS
You also can inject the
UriInfo
in your REST endpoints:And get some useful information, such as the base URI and the absolute path of the request. It will be useful when building the URI for redirection.
A resource method with redirection will be like: