Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Online Training

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
Print Button
 
Training Index

JavaTM Programming Language Basics, Part 1
Lesson 5: Writing Servlets

[<<BACK] [CONTENTS] [NEXT>>]

A servlet is an extension to a server that enhances the server's functionality. The most common use for a servlet is to extend a web server by providing dynamic web content. Web servers display documents written in HyperText Markup Language (HTML) and respond to user requests using the HyperText Transfer Protocol (HTTP). HTTP is the protocol for moving hypertext files across the internet. HTML documents contain text that has been marked up for interpretation by an HTML browser such as Netscape.

Servlets are easy to write. All you need is the Java® 2 Platform software, and JavaServerTM Web Development Kit (JWSDK). You can download a free copy of the JWSDK.

This lesson shows you how to create a very simple form that invokes a basic servlet to process end user data entered on the form.


About the Example

A browser accepts end user input through an HTML form. The simple form used in this lesson has one text input field for the end user to enter text and a Submit button. When the end user clicks the Submit button, the simple servlet is invoked to process the end user input.

In this example, the simple servlet returns an HTML page that displays the text entered by the end user.

HTML Form

The HTML form is embedded in this HTML file. The diagram shows how the HTML page looks when it is opened in a browser.

The HTML file and form are similar to the simple application and applet examples in Lesson 4 so you can compare the code and learn how servlets, applets, and applications handle end user inputs.

When the user clicks the Click Me button, the servlet gets the entered text, and returns an HTML page with the text.

The HTML page returned to the browser by the ExampServlet.java servlet is shown below. The servlet code to retrieve the user's input and generate the HTML page follows with a discussion.


Note: To run the example, you have to put the servlet and HTML files in the correct directories for the Web server you are using. For example, with Java WebServer 1.1.1, you place the servlet in the ~/JavaWebServer1.1.1/servlets and the HTML file in the ~/JavaWebServer1.1.1/public_html directory.

Servlet Backend

ExampServlet.java builds an HTML page to return to the end user. This means the servlet code does not use any Project Swing or Abstract Window Toolkit (AWT) components or have event handling code. For this simple servlet, you only need to import these packages:
  • java.io for system input and output. The HttpServlet class uses the IOException class in this package to signal that an input or output exception of some kind has occurred.

  • javax.servlet, which contains generic (protocol-independent) servlet classes. The HttpServlet class uses the ServletException class in this package to indicate a servlet problem.

  • javax.servlet.http, which contains HTTP servlet classes. The HttpServlet class is in this package.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExampServlet extends HttpServlet {
  public void doPost(HttpServletRequest request, 
	 HttpServletResponse response)
        throws ServletException, IOException
  {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<title>Example</title>" +
       "<body bgcolor=FFFFFF>");

    out.println("<h2>Button Clicked</h2>");

    String DATA = request.getParameter("DATA");

    if(DATA != null){
      out.println(DATA);
    } else {
      out.println("No text entered.");
    }

    out.println("<P>Return to 
	<A HREF="../simpleHTML.html">Form</A>");
    out.close();
  }
}

Class and Method Declarations

All servlet classes extend the HttpServlet abstract class. HttpServlet simplifies writing HTTP servlets by providing a framework for handling the HTTP protocol. Because HttpServlet is abstract, your servlet class must extend it and override at least one of its methods. An abstract class is a class that contains unimplemented methods and cannot be instantiated itself.
public class ExampServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
         HttpServletResponse response)
         throws ServletException, IOException
  {
The ExampServlet class is declared public so the web server that runs the servlet, which is not local to the servlet, can access it.

The ExampServlet class defines a doPost method with the same name, return type, and parameter list as the doPost method in the HttpServlet class. By doing this, the ExampServlet class overrides and implements the doPost method in the HttpServlet class.

The doPost method performs the HTTP POST operation, which is the type of operation specified in the HTML form used for this example. The other possibility is the HTTP GET operation, in which case you would implement the doGet method instead.

In short, POST requests are for sending any amount of data directly over the connection without changing the URL, and GET requests are for getting limited amounts of information appended to the URL. POST requests cannot be bookmarked or emailed and do not change the Uniform Resource Locators (URL) of the response. GET requests can be bookmarked and emailed and add information to the URL of the response.

The parameter list for the doPost method takes a request and a response object. The browser sends a request to the servlet and the servlet sends a response back to the browser.

The doPost method implementation accesses information in the request object to find out who made the request, what form the request data is in, and which HTTP headers were sent, and uses the response object to create an HTML page in response to the browser's request. The doPost method throws an IOException if there is an input or output problem when it handles the request, and a ServletException if the request could not be handled. These exceptions are handled in the HttpServlet class.

Method Implementation

The first part of the doPost method uses the response object to create an HTML page. It first sets the response content type to be text/html, then gets a PrintWriter object for formatted text output.
response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<title>Example</title>" +
       "<body bgcolor=#FFFFFF>");

    out.println("<h2>Button Clicked</h2>");
The next line uses the request object to get the data from the text field on the form and store it in the DATA variable. The getparameter method gets the named parameter, returns null if the parameter was not set, and an empty string if the parameter was sent without a value.
    String DATA = request.getParameter("DATA");
The next part of the doPost method gets the data out of the DATA parameter and passes it to the response object to add to the HTML response page.
    if(DATA != null){
      out.println(DATA);
    } else {
      out.println("No text entered.");
    }
The last part of the doPost method creates a link to take the end user from the HTML response page back to the original form, and closes the response.
    out.println("<P>Return to
        <A HREF="../simpleHTML.html">Form</A>");
    out.close();
  }

Note: To learn how to use the other methods available in the HttpServlet, HttpServletRequest, and HttpServletResponse classes, see The Java Tutorial trail on Servlets.

More Information

You can find more information on servlets in the Servlets trail in The Java Tutorial.

[TOP]


Print Button
[ This page was updated: 31-Mar-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.