8

I want to forward a REST request to another server.

I use JAX-RS with Jersey and Tomcat. I tried it with setting the See Other response and adding a Location header, but it's not real forward.

If I use:

request.getRequestDispatcher(url).forward(request, response); 

I get:

  • java.lang.StackOverflowError: If the url is a relative path
  • java.lang.IllegalArgumentException: Path http://website.com does not start with a / character (I think the forward is only legal in the same servlet context).

How can I forward a request?

4

1 回答 1

9

向前

允许您将RequestDispatcher来自 servlet 的请求转发到同一服务器上的另一个资源。有关更多详细信息,请参阅此答案

您可以使用JAX-RS 客户端 API并使您的资源类充当代理以将请求转发到远程服务器:

@Path("/foo")
public class FooResource {

    private Client client;

    @PostConstruct
    public void init() {
        this.client = ClientBuilder.newClient();
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod() {

        String entity = client.target("http://example.org")
                              .path("foo").request()
                              .post(Entity.json(null), String.class);   

        return Response.ok(entity).build();
    }

    @PreDestroy
    public void destroy() {
        this.client.close();
    }
}

重定向

如果重定向适合您,您可以使用ResponseAPI:

请参阅示例:

@Path("/foo")
public class FooResource {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod() {

        URI uri = // Create your URI
        return Response.temporaryRedirect(uri).build();
    }
}

可能值得一提的是,UriInfo可以在你的资源类或方法中注入一些有用的信息,例如请求的基本 URI绝对路径

@Context
UriInfo uriInfo;
于 2015-10-15T14:06:57.353 回答