自定义响应头 Jersey/Java [英] Custom response header Jersey/Java

查看:23
本文介绍了自定义响应头 Jersey/Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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");
    ...
}

这篇关于自定义响应头 Jersey/Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆