Custom response header Jersey/Java

I am trying to achieve the following.

Read a custom header and its value from Request:

name: username

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

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

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

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!

Answers


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

I think using javax.ws.rs.core.Response is more elegant and it is a part of Jersey. Just to extend previous answer, here is a simple example:

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/values")
    public Response getValues(String body) {

        //Prepare your entity

        Response response = Response.status(200).
                entity(yourEntity).
                header("yourHeaderName", "yourHeaderValue").build();

        return response;
    }

Return a Response (a class from JAX-RS) with UserClass as the entity. On the Response you can set HTTP headers.


Need Your Help

How to use a xib and a UIView subclass together?

iphone objective-c cocoa-touch ios interface-builder

I'd like to create a couple of custom views, sort of reusable UI components, and would prefer to not layout the UI in code in the UIView subclass. I'd like to use a xib for that. I've used a xib by

What is a cache hit and a cache miss? Why would context-switching cause cache miss?

concurrency language-agnostic cpu cpu-architecture cpu-cache

From the 11th Chapter(Performance and Scalability) and the section named Context Switching of the JCIP book: