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.


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


    <script src="">
<button onclick="getHeader()">Header request</button>
<div id="header-content"></div>

 function getHeader(){
                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/>";
                      response +=  v +" <br/>";
                error: function(xhr, status, error){
                  .html('<span style=\'color:red;\'>'+error+'</span>')

The Servlet

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

  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


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
          • webapp

    See Also