Monday, March 7, 2011

Chapter 12: Retrieving HTTP Request Header Information

In the Previous Chapter we saw how to get a Servlets Initialization parameters. In this chapter, we are going to take a look at how to get the Header information from the Http Request.

So, lets get started!!!

Retrieving HTTP Request Header Information

The Http Request header is the area where all the details of the request are bundled. This is where the browser specifies the file wanted, date, image file support, and a lot more. Let us take a look at a sample Servlet that is going to read through the Http Request Header.

Servlet code:

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

/**
* Displaying request headers
*
* @author Anand V
*/

public class ReadHttpRequestHeaderServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");

PrintWriter out = response.getWriter();
out.println("< html >");
out.println("< head >");

String title = "Read Request Header Example";
out.println("< title >" + title + "");
out.println("< / head >");
out.println("< body >");

out.println("< h3 >" + title + "< / h3 >");
out.println("< table >");
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements())
{
String headerName = (String)e.nextElement();
String headerValue = request.getHeader(headerName);
out.println("< tr >< td bgcolor=\"#CCCCCC\" > " + headerName);
out.println("< / td >< td > " + headerValue + " < / td > < / tr >");
}
out.println("< / table >");
out.println("< / body >");
out.println("< / html >");
}
}

When you deploy this Servlet on your local tomcat server you will see something like below:



Previous Chapter: Chapter 11 - Obtaining a Servlets Initialization Parameters

Next Chapter: Chapter 13 - Web Application Scope

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers