Java
  Home arrow Java arrow Page 6 - An Introduction to Java Servlets
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

An Introduction to Java Servlets
By: Nakul Goyal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 43
    2002-03-11

    Table of Contents:
  • An Introduction to Java Servlets
  • The dark ages
  • Servlets to the rescue!
  • The servlet runtime environment
  • Servlet interface and life cycle
  • Request and response objects
  • Persistent and Shared Data
  • ServletContext attributes
  • Request attributes and resources
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    An Introduction to Java Servlets - Request and response objects


    (Page 6 of 10 )

    The doGet method has two interesting parameters: HttpServletRequest and HttpServletResponse. These two objects give us full access to all information about the request and let us control the output sent to the client as the response to the request.

    With CGI you read environment variables and stdin to get information about the request, however the naming convention of environment variables may vary between CGI implementations, and some variables are not provided by all Web servers.

    The HttpServletRequest object provides the same information as the CGI environment variables and more, in a standardized way. It also provides methods for extracting HTTP parameters from the query string or the request body depending on the type of request (GET or POST). As a servlet developer, you access parameters the same way for both types of requests. Other methods give you access to all request headers and help you parse date and cookie headers.

    Instead of writing the response to stdout as you would with traditional CGI, you receive an OutputStream or a PrintWriter object from the HttpServletResponse. The OuputStream is intended for binary data, such as a GIF or JPEG image, and the PrintWriter for text output. You can also set all response headers and the status code, without having to rely on special Web server CGI configurations such as Non Parsed Headers (NPH). This makes your servlet even easier to install.

    Let's implement the body of our doGet method and see how we can use these methods. We will read most of the information we can get from the HttpServletRequest (saving some methods for the next example) and send those values as a response to the request.

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    // Print the HTML header

    out.println("<HTML><HEAD><TITLE>");

    out.println("Request info");

    out.println("</TITLE></HEAD>");

    // Print the HTML body

    out.println("<BODY><H1>Request info</H1><PRE>");

    out.println("getCharacterEncoding: " + request.getCharacterEncoding());

    out.println("getContentLength: " + request.getContentLength());

    out.println("getContentType: " + request.getContentType());

    out.println("getProtocol: " + request.getProtocol());

    out.println("getRemoteAddr: " + request.getRemoteAddr());

    out.println("getRemoteHost: " + request.getRemoteHost());

    out.println("getScheme: " + request.getScheme());

    out.println("getServerName: " + request.getServerName());

    out.println("getServerPort: " + request.getServerPort());

    out.println("getAuthType: " + request.getAuthType());

    out.println("getMethod: " + request.getMethod());

    out.println("getPathInfo: " + request.getPathInfo());

    out.println("getPathTranslated: " + request.getPathTranslated());

    out.println("getQueryString: " + request.getQueryString());

    out.println("getRemoteUser: " + request.getRemoteUser());

    out.println("getRequestURI: " + request.getRequestURI());

    out.println("getServletPath: " + request.getServletPath());

    out.println();

    out.println("Parameters:");

    Enumeration paramNames = request.getParameterNames();

    while (paramNames.hasMoreElements()) {

    String name = (String) paramNames.nextElement();

    String[] values = request.getParameterValues(name);

    out.println(" " + name + ":");

    for (int i = 0; i < values.length; i++) {

    out.println(" " + values[i]);

    }

    }

    out.println();

    out.println("Request headers:");

    Enumeration headerNames = request.getHeaderNames();

    while (headerNames.hasMoreElements()) {

    String name = (String) headerNames.nextElement();

    String value = request.getHeader(name);

    out.println(" " + name + " : " + value);

    }

    out.println();

    out.println("Cookies:");

    Cookie[] cookies = request.getCookies();

    for (int i = 0; i < cookies.length; i++) {

    String name = cookies[i].getName();

    String value = cookies[i].getValue();

    out.println(" " + name + " : " + value);

    }

    // Print the HTML footer

    out.println("</PRE></BODY></HTML>");

    out.close();

    }


    The doGet method above uses most of the methods in HttpServletRequest that provide information about the request. You can read all about them in the servlet API documentation so here we'll just look at the most interesting ones.

    getParameterNames and getParameterValues help you access HTTP parameters no matter if the servlet was requested with the GET or the POST method. getParameterValues returns a String array because an HTTP parameter may have multiple values. For instance, if you request the servlet with a URL like http://nakul.net/servlet/ReqInfoServlet?foo=bar&foo=baz, then you'll see that the foo parameter has two values: bar and baz. The same is true if you use an identical name for more than one HTML form element and use the POST method in its ACTION tag.

    If you're sure that an HTTP parameter can only have one value, then you can use the getParameter method instead of getParameterValues. It returns a single string and if there are multiple values it returns the first value received with the request.

    You have access to all HTTP request headers with the getHeaderNames and getHeader methods. getHeader returns the String value of the header. If you know that the header has a date value or an integer value you can get help converting the header to an appropriate format. getDateHeader returns a date as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This is the standard numeric representation of a timestamp in Java (as well as Unix), and you can use it to construct a Date object for further manipulation. getIntHeader returns the header value as an int.

    getCookies parses the Cookie header and returns all cookies as an array of Cookie objects. To add a cookie to a response, the HttpServletResponse class provides an addCookie method that takes a Cookie object as its argument. This saves you from dealing with the format for different versions of the cookie header string.

    If you compile the ReqInfoServlet and install it in your servlet engine, then you can invoke it through a browser with a URL like http://nakul.net/servlet/ReqInfoServlet/foo/bar?fee=baz. If everything goes as planned you will see something like this in your browser:

    Request info

    getCharacterEncoding:

    getContentLength: -1

    getContentType: null

    getProtocol: HTTP/1.0

    getRemoteAddr: 127.0.0.1

    getRemoteHost: localhost

    getScheme: http

    getServerName: nakul.net

    getServerPort: 80

    getAuthType: null

    getMethod: GET

    getPathInfo: /foo/bar

    getPathTranslated: D:\PROGRA~1\jsdk2.1\httproot\servlet\ReqInfoServlet\foo\bar

    getQueryString: fee=baz

    getRemoteUser: null

    getRequestURI: /servlet/ReqInfoServlet/foo/bar

    getServletPath: /servlet/ReqInfoServlet

    Parameters:

    fee:

    baz

    Request headers:

    Connection : Keep-Alive

    User-Agent : Mozilla/4.5 [en] (WinNT; I)

    Host : nakul.net

    Accept : image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*

    Accept-Encoding : gzip

    Accept-Language : en

    Accept-Charset : iso-8859-1,*,utf-8

    Cookie : TOMCATID=TO04695278486734222MC1010AT

    Cookies:

    TOMCATID : TO04695278486734222MC1010AT

    What if you want this servlet to handle both GET and POST requests? The default implementations of doGet and doPost return a message saying that the method is not yet implemented. So far we have only provided a new implementation of doGet. To handle a POST request in the same way, we can simply call doGet from doPost:

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    doGet(request, response);

    }

    More Java Articles
    More By Nakul Goyal


     

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT