Retrieving header parameters in JAX-RS annotated method

The post explains different ways of retrieving header parameters in JAX-RS annotated method.

Below is the complete code


1  package resource;
2  
3  import javax.ws.rs.GET;
4  import javax.ws.rs.HeaderParam;
5  import javax.ws.rs.Path;
6  import javax.ws.rs.core.Context;
7  import javax.ws.rs.core.HttpHeaders;
8  import javax.ws.rs.core.MediaType;
9  import javax.ws.rs.core.Response;
10 
11 @Path("webresource3")
12 public class WebResource3 {
13  @GET
14  @Path("headerParameters1")
15  public Response getHeaderParameters1(@HeaderParam("param1") String param1) {
16      Response response = Response.ok(param1, MediaType.TEXT_PLAIN).build();
17      return response;
18  }
19  
20  @GET
21  @Path("headerParameters2")
22  public Response getHeaderParameters2(@Context HttpHeaders headers) {
23      String value = headers.getRequestHeader("param1").get(0);
24      Response response = Response.ok(value, MediaType.TEXT_PLAIN).build();
25      return response;
26  }
27 }

The above web resource can be accessed using the below two urls
http://localhost:8080/JAXRSConcepts/myresources/webresource3/headerParameters1
http://localhost:8080/JAXRSConcepts/myresources/webresource3/headerParameters2

In the first method getHeaderParameters1, the variable param1 is annotated by HeaderParam. This to inform to the JAX-RS runtime that the value has to be taken from the request header using header name passed to the HeaderParam annotation (i.e., in this param1) and inject the value to the variable param1.

In the second method getHeaderParameters2, we use the Context annotation. This annotation is used to inject context information, in this case HttpHeaders instance. HttpHeaders instance provides request header information. Once you get the HttpHeaders instance, we can get the param1 header information as shown in
the above code at line 23.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s