Monday, October 8, 2012
Today I am going to post a program that will be able to show all the headers associated with a servlet request;  Here in the code request object is used to get an enumerations of headers associated with the request of the client. Then with a loop one by one all the headers are extracted and their corresponding values are available using the getHeader(String headername) method. All these headers and their values are sent to the client as a dynamically generated html. Also note that the values will differ according to the browser which has been used to send the request.
Screenshot of output as seen on Chrome in Windows7
Here is the code for you -->

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

public class HeaderViewer extends HttpServlet{

   public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
          Enumeration headers=req.getHeaderNames(); 
/*getting enumerations of all headers */
          PrintWriter out=res.getWriter(); 
//getting writer
          out.write("<body><h1><center>Headers associated with your request</center></h1>");
                 String header=(String)headers.nextElement(); 
/*extracting header */
                 out.write("</br><b>"+header+" : </b>"+req.getHeader(header));
/* sending header name and its value to client */


Post a Comment

Total Pageviews

Subscribe via Email


Popular Posts