简体   繁体   English

从 JAX-RS 服务发送重定向

[英]Send redirect from a JAX-RS service

Is it possible to have a JAX-RS web service redirect to another web page?是否可以将 JAX-RS Web 服务重定向到另一个网页?

Like as you would do with Servlet response.sendRedirect("http://test/test.html") .就像您对 Servlet response.sendRedirect("http://test/test.html")

The JAX-RS web service should itself redirect. JAX-RS Web 服务本身应该重定向。 I'm using RESTEasy if that's relevant.如果相关,我正在使用 RESTEasy。

Yes, you can do this in Jersey or any JAX-RS implementation (including RestEasy) if your return type is a Response (or HttpServletResponse ) https://eclipse-ee4j.github.io/jersey.github.io/apidocs/1.19.1/jersey/javax/ws/rs/core/Response.html是的,如果您的返回类型是Response (或HttpServletResponse ),您可以在 Jersey 或任何 JAX-RS 实现(包括 RestEasy)中执行此操作https://eclipse-ee4j.github.io/jersey.github.io/apidocs/1.19 .1/球衣/javax/ws/rs/core/Response.html

You can use either of the following:您可以使用以下任一项:

Response.temporaryRedirect(URI)

Response.seeOther(URI)

"Temporary Redirect" returns a 307 status code while "See Other" returns 303. “临时重定向”返回 307 状态代码,而“查看其他”返回 303。

For those like me looking for 302 that fall on this answer.对于像我这样正在寻找 302 的人来说,这个答案。

By looking the code of通过查看代码

Response.temporaryRedirect(URI)

You can customize your response code like this :您可以像这样自定义响应代码:

Response.status(int).location(URI).build()

Note that status code are define in enum请注意,状态代码在枚举中定义

Response.Status

And for example 302 is Response.Status.FOUND例如 302 是Response.Status.FOUND

Extending smcg@ answer above,扩展上面的 smcg@ 答案,

You can achieve this by altering the request context in a ContainerRequestFilter by using ContainerRequestContext.setRequestUri(URI) .您可以通过使用ContainerRequestContext.setRequestUri(URI)更改ContainerRequestFilter的请求上下文来实现此目的。 If you see the JAX-RS specification (Section 6.2) here , there is a mention of @PreMatching request filters.如果您在此处看到 JAX-RS 规范(第 6.2 节),则会提到@PreMatching请求过滤器。 According to the documentation;根据文档;

A ContainerRequestFilter that is annotated with @PreMatching is executed upon receiving a client request but before a resource method is matched.使用 @PreMatching 注释的 ContainerRequestFilter 在收到客户端请求后但在匹配资源方法之前执行。 Thus, this type of filter has the ability to modify the input to the matching algorithm (see Section 3.7.2) and, consequently, alter its outcome.因此,这种类型的过滤器能够修改匹配算法的输入(参见第 3.7.2 节),从而改变其结果。

A very naive filter can be like this;一个非常幼稚的过滤器可能是这样的;

@PreMatching
class RedirectFilter: ContainerRequestFilter {
    override fun filter(requestContext: ContainerRequestContext?) {

      requestContext!!.setRequestUri(URI.create("<redirect_uri>"))
    }
}

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

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