Dec 21, 2010

Reading stuffs in a HTTP Request

A HTTP Request has unimaginably more content than you think it will have. In Java Server programming, all your requests are contained in a HTTPRequest object and you are supposed to read the request and send back a response.
There are certain common or business fields that you may want to preserve across the application. Like the logged-in user's name, or a shopping cart that contains the list of items that the customer added to his cart. You have three options to store/retrieve such general details. Header, Session and Cookies.
Below is a piece of Java Servlet code that will help read HTTPHeaders, HTTPSession variables, and HTTPCookies. Based on your situation, you can add conditions/modify them as per your needs.

Code to read the available cookies:
Cookie[] cookies = request.getCookies();
if ((cookies != null) && (cookies.length > 0)) {
  for (int i = 0; i < cookies.length; i++) {
   Cookie cookie = cookies[i];
    System.out.print("Cookie Name: " + cookie.getName());
     System.out.println("  Cookie Value: " + cookie.getValue());
     }
   } 
else{
System.out.println("no cookies found");
     }

Code to read the available variables in the HTTP Header:

java.util.Enumeration names = request.getHeaderNames();
  while (names.hasMoreElements())
   {
    String name = (String) names.nextElement();
    System.out.print(" "+name+": "+request.getHeader(name));
   }        

Use this code to read the available variables in the HTTP Session object.

java.util.Enumeration sessionVars = request.getSession().getAttributeNames();
while (sessionVars.hasMoreElements())
{
String name = (String) sessionVars.nextElement();
System.out.print(" "+name+": "+request.getSession().getAttribute(name));
}        
     

No comments:

Post a Comment

You may also like these writeups

Related Posts with Thumbnails