How do I display request headers?
Author: Deron Eriksson
Description: This tutorial describes how to enumerate over request headers.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20

In a servletW, it's possible to get an enumeration of the request headers with a call to the request's getHeaderNames() method. We can enumerate over the list of header names, and call request.getHeader(headerName) to get the value of each header name. This is illustrated below.

package test;

import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DisplayRequestHeadersServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		doPost(request, response);

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

		PrintWriter out = response.getWriter();
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = headerNames.nextElement();
			out.print("Header Name: <em>" + headerName);
			String headerValue = request.getHeader(headerName);
			out.print("</em>, Header Value: <em>" + headerValue);


If I hit the servlet code above with a web browser, I see the following result:

Displaying request headers

In this example, probably the most useful header value is the "user-agent", which tells the servlet the browser/platform that is hitting the servlet.