Home » Displaying all the header information in the servlet

Displaying all the header information in the servlet

by Online Tutorials Library

Displaying all the header information in the servlet

The getHeaderNames() of ServletRequest interface returns an Enumeration object, containing all the header names. The getHeader() method of ServletRequest interface returns the header value for the given header name. In this example, we are displaying all the header information of a request in the servlet page.

Syntax of getHeaderNames() method

  public Enumeration getHeaderNames()    

Syntax of getHeader() method

  public String getHeader(String headerName)    

Example of displaying all the header information in the servlet

In this example, we are calling the getHeaderNames() method of the ServletRequest interface, which returns the Enumeration object containing all the header names. By calling the getHeader() method, we are displaying all the header values. Let’s see the example:

index.html

  <a href="run"> click Here </a>    

ShowHeaders.java

  import java.io.*;  import javax.servlet.*;  import javax.servlet.http.*;  import java.util.*;    public class ShowHeaders extends HttpServlet {      public void doGet(HttpServletRequest request,                      HttpServletResponse response)      throws IOException, ServletException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();                out.println("HTTP headers sent by your client:<br>");          Enumeration enum = request.getHeaderNames();          while (enum.hasMoreElements()) {          String headerName = (String) enum.nextElement();          String headerValue = request.getHeader(headerName);          out.print("<b>"+headerName + "</b>: ");          out.println(headerValue + "<br>");        }            }  }      

You may also like