自定义响应头 Jersey/Java自定义、Jersey、Java

2023-09-06 11:10:31 作者:—似水年华

我正在努力实现以下目标.

I am trying to achieve the following.

从 Request 中读取自定义标头及其值:

Read a custom header and its value from Request:

name: username

现在,在响应时,我想在 HTTP 响应中返回相同的标头 name:value 对.

Now, on response, I would like to return the same header name:value pair in HTTP response.

我正在使用 JAX-RS 网络服务的 Jersey 2.0 实现.

I am using Jersey 2.0 implementation of JAX-RS webservice.

当我发送请求 URL Http://localhost/test/ 时,请求标头也被传递(暂时,虽然 Firefox 插件 - 硬编码它们).

When I send the request URL Http://localhost/test/, the request headers are also passed (for the time being, though Firefox plugin - hardcoding them).

收到对该 URL 的请求后,将调用以下方法:

On receiving the request for that URL, the following method is invoked:

@GET
@Produces(MediaType.APPLICATION_JSON)
public UserClass getValues(@Context HttpHeaders header) {
    MultivaluedMap<String, String> headerParams = header.getRequestHeaders();
    String userKey = "name";
    headerParams.get(userKey);

    // ...

    return user_object;
}

我怎样才能做到这一点?任何指针都会很棒!

How may I achieve this? Any pointers would be great!

推荐答案

只需注入一个 @Context HttpServletResponse 响应 作为方法参数.更改标题

Just inject a @Context HttpServletResponse response as a method argument. Change the headers on that

@Produces(MediaType.APPLICATION_JSON)
public UserClass getValues(@Context HttpHeaders header, @Context HttpServletResponse response) {
    response.setHeader("yourheadername", "yourheadervalue");
    ...
}