ZetCode

Java Servlet HTTP headers

last modified August 24, 2023

In this article 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.

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           └── MyServlet.java
    │   ├── resources
    │   └── webapp
    │       ├── showHeaders.jsp
    │       └── WEB-INF
    └── test
        └── java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>HttpServletMappingEx</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>11.0.11</version>
                <configuration>
                    <webApp>
                        <contextPath>/app</contextPath>
                    </webApp>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

This is the pom.xml file.

com/zetcode/ShowHeaders.java
package com.zetcode;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;


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

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

        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.

Navigate to localhost:8080/app/ShowHeaders to get the headers through a servlet.

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.

webapp/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.

Navigate to localhost:8080/app/showHeaders.jsp to get the headers through a JSP.

In this article we worked with HTTP header fields.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java Servlet tutorials.