[英]How to forward a request using JAX-RS?
我想将REST请求转发到另一台服务器。
我将JAX-RS与Jersey和Tomcat一起使用。 我尝试通过设置See Other
响应并添加Location
标头来进行尝试,但这并不是真正的前进。
如果我使用:
request.getRequestDispatcher(url).forward(request, response);
我得到:
java.lang.StackOverflowError
:如果url是相对路径 java.lang.IllegalArgumentException
:路径http://website.com不能以/
字符开头(我认为转发仅在同一servlet上下文中是合法的)。 如何转发请求?
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();
}
}
如果重定向适合您,则可以使用Response
API:
Response.seeOther(URI)
:在POST后重定向(也称为POST / redirect / GET)模式中使用。 Response.temporaryRedirect(URI)
:用于临时重定向。 参见示例:
@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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.