September 28, 2011

Retrieve Request Headers in a Servlet

1) Create a Java Servlet class - HeaderTest.java - in the src folder of the Web Application

package info.icontraining.servlets;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderTest extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
                     throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();

      Enumeration e = request.getHeaderNames();
      String headerName = null;

      while(e.hasMoreElements()) {
         headerName = (String) e.nextElement();
         out.println(headerName + ": "); 
         out.println(request.getHeader(headerName) + "\n");
      }
  
      out.close();
   }
}

2) Configure the servlet in the web.xml deployment descriptor in the WebContent/WEB-INF folder

<servlet>
   <servlet-name>headerTest</servlet-name>
   <servlet-class>info.icontraining.servlets.HeaderTest</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>headerTest</servlet-name>
   <url-pattern>/headerTest</url-pattern>
</servlet-mapping>

3) Test the servlet with the following URL in the browser,

http://localhost:8080/WebAppName/headerTest

No comments:

Post a Comment