简体   繁体   English

如何使用JAX-RS转发请求?

[英]How to forward a request using JAX-RS?

I want to forward a REST request to another server. 我想将REST请求转发到另一台服务器。

I use JAX-RS with Jersey and Tomcat. 我将JAX-RS与Jersey和Tomcat一起使用。 I tried it with setting the See Other response and adding a Location header, but it's not real forward. 我尝试通过设置See Other响应并添加Location标头来进行尝试,但这并不是真正的前进。

If I use: 如果我使用:

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

I get: 我得到:

  • java.lang.StackOverflowError : If the url is a relative path java.lang.StackOverflowError :如果url是相对路径
  • 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). java.lang.IllegalArgumentException :路径http://website.com不能以/字符开头(我认为转发仅在同一servlet上下文中是合法的)。

How can I forward a request? 如何转发请求?

Forward 向前

The RequestDispatcher allows you to forward a request from a servlet to another resource on the same server . RequestDispatcher允许您将请求从Servlet转发到同一服务器上的另一个资源。 See this answer for more details. 有关更多详细信息,请参见此答案

You can use the JAX-RS Client API and make your resource class play as a proxy to forward a request to a remote server: 您可以使用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();
    }
}

Redirect 重新导向

If a redirect suits you, you can use the Response API: 如果重定向适合您,则可以使用Response API:

See the example: 参见示例:

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

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

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

It may be worth it to mention that UriInfo can be injected in your resource classes or methods to get some useful information, such as the base URI and the absolute path of the request . 值得一提的是,可以将UriInfo注入您的资源类或方法中以获得一些有用的信息,例如基本URI请求绝对路径

@Context
UriInfo uriInfo;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM