Close

JAX-RS - @HEAD Examples

[Last Updated: Jun 4, 2017]

In JAX-RS, an incoming HTTP HEAD request is handled by a target resource method successfully if:

  • The resource method is annotated with @HEAD.
  • The resource method annotated with @GET, any returned entity is discarded for HTTP HEAD request, but for HTTP GET request, it will function normally.

Let's see examples to understand how to handle HTTP HEAD requests.

HTTP HEAD request with @HEAD method

The resource method

@Path("/")
public class ExampleResource {

  @Path("/test")
  @HEAD
  public Response handle(@QueryParam("param1") String param1) {
      System.out.printf("param1: %s%n", param1);
      Response r = Response.ok("this body will be ignored")
                           .header("someHeader", "someHeaderValue")
                           .build();
      return r;
  }
    .............
}

Client request

public class MyClient {
  public static void main(String[] args) {
      MyClient.sendHeadRequest("test");
  }

  public static void sendHeadRequest(String uri) {
      Client client = ClientBuilder.newClient();
      WebTarget target = client.target("http://localhost:8080/app/" + uri);
      Response response = target.request()
                                .head();
      MultivaluedMap<String, Object> headers = response.getHeaders();
      System.out.printf("headers: %s%n", headers);
      System.out.printf("status: %s%n", response.getStatus());
      System.out.printf("body: '%s'%n", response.readEntity(String.class));
  }
}

Output

headers: {Server=[Apache-Coyote/1.1], someHeader=[someHeaderValue], Content-Length=[25], Date=[Wed, 31 May 2017 01:27:53 GMT], Content-Type=[text/html]}
status: 200
body: ''

HTTP HEAD request with @GET method

The resource method

@Path("/")
public class ExampleResource {
    .............
  @Path("/test2")
  @GET
  public Response handle2() {
      Response r = Response.ok("some body content")
                           .header("someHeader2", "someHeaderValue2")
                           .build();
      return r;
  }
    .............
}

Client request

public class MyClient2 {
  public static void main(String[] args) {
      MyClient.sendHeadRequest("test2");
  }
}

Output

headers: {Server=[Apache-Coyote/1.1], Content-Length=[17], Date=[Wed, 31 May 2017 01:03:02 GMT], Content-Type=[text/html], someHeader2=[someHeaderValue2]}
status: 200
body: ''

HTTP HEAD request from JQuery to @HEAD method

The resource method

@Path("/")
public class ExampleResource {

  @Path("/test")
  @HEAD
  public Response handle(@QueryParam("param1") String param1) {
      System.out.printf("param1: %s%n", param1);
      Response r = Response.ok("this body will be ignored")
                           .header("someHeader", "someHeaderValue")
                           .build();
      return r;
  }
    .............
}

The HTML page

src/main/webapp/myPage.html

<html>
<head>
    <script
            src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">
    </script>
</head>
<body>
<h2>My page</h2>
<form id="my-form">
    <pre>
         Enter request query param   <input type="text" name="param1"/><br/>
                         <input type="submit" value="Submit"/>
    </pre>
</form>
<div id="msg"></div>
<script>
 $("#my-form").submit(function(event){
            event.preventDefault();
            var $form = $(this);
            var queryParamVal = $form.find('input[name="param1"]').val();
            var url = "http://localhost:8080/app/test?param1="+queryParamVal;
            $.ajax({
                type : 'HEAD',
                url : url,
                success : function(data, status, xhr){
                    $('#msg').html('status: '+status+
                    '<br/>Header someHeader value: '+
                     xhr.getResponseHeader('someHeader'));
                },
                error: function(xhr, status, error){
                $('#msg').html('<span style=\'color:red;\'>'+error+'</span>')
                }
            });
        });
</script>
</body>
</html>

Note that, in above example, myPage.html is handled by the servlet container (context root is '/', see pom.xml in project browser below), whereas, our JAX-RS application root is '/app' (see MyRestApp.java); we kept it that way. If our JAX-RS root was also '/' then myPage.html would return 404 error.

Example Project

Dependencies and Technologies Used:

  • jersey-server 2.25.1: Jersey core server implementation.
  • jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
  • JDK 1.8
  • Maven 3.3.9

Jaxrs Head Example Select All Download
  • jaxrs-head-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleResource.java
          • webapp

    See Also