Java Servlet HTTP headers

In this tutorial, we talk about HTTP headers and show how to display HTTP headers in a Java servlet and a JSP file.

HTTP header fields are components of the header section of request and response messages in the Hypertext Transfer Protocol (HTTP). They define the operating parameters of an HTTP transaction.

HTTP headers allow the client and the server to pass additional information with the request or the response. They are used for various tasks such as authentication, cookies, caching, connection management, or content negotiation.

For instance, the User-Agent specifies the user aget (the client application that made the request such as browser) and Date specifies the date and time when the message was originated.

There are several types of headers:

Showing header fields with a Java servlet

In the first example, we display HTTP headers in a servlet.

ShowHeaders.java
package com.zetcode.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ShowHeaders", urlPatterns = {"/ShowHeaders"})
public class ShowHeaders extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try (PrintWriter out = response.getWriter()) {
            
            response.setContentType("text/html");
            out.println("<!DOCTYPE html>");
            out.println("<html lang=\"en\">");
            out.println("<head>");
            out.println("<title>HTTP headers</title>"); 
            out.println("<body>"); 
            out.println("<p>Headers</p>");
            
            Enumeration<String> headerNames = request.getHeaderNames();
            
            out.println("<ol>");
            while (headerNames.hasMoreElements()) {
                out.print("<li>");
                String headerName = headerNames.nextElement();
                out.print(headerName + " = ");
                String headerValue = request.getHeader(headerName);
                out.print(headerValue);
                out.println("</li>");
            }
            out.println("</ol>");
            
            out.println("</body>");
            out.println("</html>");
        }
    }
}

The ShowHeaders servlet finds out HTTP headers sent by the client and sends them back in a HTML file.

PrintWriter out = response.getWriter()

We directly write to the PrintWriter. Note that while it is possible to do this direct writing, modern Java web applications use templates such as Thymeleaf, FreeMarker, or JSP to create HTML pages.

response.setContentType("text/html");

The content type of the response is set to text/html.

Enumeration<String> headerNames = request.getHeaderNames();

We get the header names with the getHeaderNames() method. It returns an enumeration of strings.

String headerName = headerNames.nextElement();

We get the next header name from the enumeration with the nextElement() method.

String headerValue = request.getHeader(headerName);

With the getHeader(), we get the header value.

Showing header fields in a JSP file

In the second example, we display HTTP headers in a JSP file. We also use the JSTL library.

showHeaders.jsp
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>HTTP headers</title>
  </head>
  <body>
    <p>HTTP headers:</p>
    <ol>
      <c:forEach var="nextHeader" items="${header}">
          <li><c:out value="${nextHeader.key}" /> = <c:out value="${nextHeader.value}" /></li>
      </c:forEach>
    </ol>
  </body>
</html>

A JSP file has a header implicit object, which is a map of header names and their values.

<c:forEach var="nextHeader" items="${header}">
    <li><c:out value="${nextHeader.key}" /> = <c:out value="${nextHeader.value}" /></li>
</c:forEach>

Using the JSTL's forEach tag, we iterate over the map and display the header names and their values.

In this tutorial, we worked with HTTP header fields.

You might also be interested in the following related tutorials: Java servlet check box tutorial, Java servlet image tutorial, Servlet FreeMarker JdbcTemplate tutorial, Serving image file in Spring Boot, Java tutorial, jQuery DatePicker tutorial, or Stripes tutorial.