Close

Servlet - doHead() Example

[Last Updated: Aug 27, 2017]

An HTTP HEAD request is similar to HTTP GET request except that no message body is sent back in the response.

In Java Servlet, HttpServlet#doHead() method is overridden to handle a HEAD request. The response message body is used to count the output bytes to send accurate Content-Length header but the message body is not attached in the response. We can avoid computing the response body and just set the response headers directly to improve performance.

Example

In this example, we will send a HEAD request from the web browser via JQuery.

src/main/webapp/index.html

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">
    </script>
</head>
<body>
<button onclick="getHeader()">Header request</button>
<br/><br/>
<div id="header-content"></div>
</body>

<script>
 function getHeader(){
            $.ajax({
                type : 'HEAD',
                url : 'http://localhost:8080/currency-rates',
                success : function(data, status, xhr){
                   var response = "<b>data:</b> "+ data +"<br/>";
                   response +=  "<b>headers:</b> <br/>";
                   $.each(xhr.getAllResponseHeaders().split("\n"),
                   function(i,v){
                      response +=  v +" <br/>";
                    });
                   $('#header-content').html(response)
                },
                error: function(xhr, status, error){
                  $('#header-content')
                  .html('<span style=\'color:red;\'>'+error+'</span>')
                }
            });
      }
</script>
</body>
</html>

The Servlet

@WebServlet(name = "currencyRateServlet", urlPatterns = {"/currency-rates"})
public class CurrencyRateServlet extends HttpServlet {
  @Override
  protected void doHead(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      doGet(req, resp);
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      PrintWriter writer = resp.getWriter();
      writer.write("some currency data ..");
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Accessing 'http://localhost:8080' and clicking on Header request button:

Example Project

Dependencies and Technologies Used:

  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Servlet Do Head Example Select All Download
  • head-request-method-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • CurrencyRateServlet.java
          • webapp

    See Also