Home arrow Java arrow Page 6 - An Introduction to Java Servlets

An Introduction to Java Servlets

Java servlets are making headlines these days, claiming to solve many of the problems associated with CGI and proprietary server API's. In this article Nakul describes the overall servlet architecture and what you need to develop a web application using servlets. He uses several coding examples to show you how to use the servlet API and compares it with CGI and proprietary server API's.

Author Info:
By: Nakul Goyal
Rating: 4 stars4 stars4 stars4 stars4 stars / 53
March 11, 2002
  1. · An Introduction to Java Servlets
  2. · The dark ages
  3. · Servlets to the rescue!
  4. · The servlet runtime environment
  5. · Servlet interface and life cycle
  6. · Request and response objects
  7. · Persistent and Shared Data
  8. · ServletContext attributes
  9. · Request attributes and resources
  10. · Conclusion

print this article

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 {


PrintWriter out = response.getWriter();

// Print the HTML header


out.println("Request info");


// 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());



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("Request headers:");

Enumeration headerNames = request.getHeaderNames();

while (headerNames.hasMoreElements()) {

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

String value = request.getHeader(name);

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




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




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


getContentLength: -1

getContentType: null

getProtocol: HTTP/1.0


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




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


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);


blog comments powered by Disqus

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- 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 ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials