O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Redirecting to Another Service

Problem

You want to redirect clients from one RESTful service to another and keep attendant details and metadata such as parameters intact.

Solution

Create a URI using javax.ws.rs.core.UriBuilder that maps the parameters and other data you want to preserve. Then use Response.temporaryRedirect to return a redirect to the client and pass it the URI you’ve built.

Discussion

The code in Example 8-25 redirects clients from one service to another. It maintains the query string that was passed in the original request. You have one service, OldService, that responds on the URI the client actually requests. It redirects to the new service.

Example 8-25. OldService.java redirects clients to the service at NewService

package com.soacookbook.rest.response; import java.net.URI; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; /** * Redirects the client from the requested URI to another, * and maintains the query parameters. */ @Path("/oldversion") public class OldService { private static final String REDIR_PATH = "http://localhost:8080/restexamples/resources/"; private static final String REDIR_SERVICE = "newversion"; @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(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required