Home > Articles > Programming > Java

This chapter is from the book

2.2 Basic Servlet Structure

Listing 2.1 outlines a basic servlet that handles GET requests. GET requests, for those unfamiliar with HTTP, are the usual type of browser requests for Web pages. A browser generates this request when the user enters a URL on the address line, follows a link from a Web page, or submits an HTML form that either does not specify a METHOD or specifies METHOD="GET". Servlets can also easily handle POST requests, which are generated when someone submits an HTML form that specifies METHOD="POST". For details on using HTML forms, see Chapter 16 of Core Servlets and JavaServer Pages (available in PDF at http://www.moreservlets.com).

Listing 2.1 ServletTemplate.java

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

public class ServletTemplate extends HttpServlet {
 public void doGet(HttpServletRequest request,
          HttpServletResponse response)
   throws ServletException, IOException {
   
  // Use "request" to read incoming HTTP headers
  // (e.g., cookies) and query data from HTML forms.
  
  // Use "response" to specify the HTTP response status
  // code and headers (e.g. the content type, cookies).
  
  PrintWriter out = response.getWriter();
  // Use "out" to send content to browser.
 }
}

To be a servlet, a class should extend HttpServlet and override doGet or doPost, depending on whether the data is being sent by GET or by POST. If you want a servlet to take the same action for both GET and POST requests, simply have doGet call doPost, or vice versa.

Both doGet and doPost take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods by which you can find out about incoming information such as form (query) data, HTTP request headers, and the client's hostname. The HttpServletResponse lets you specify outgoing information such as HTTP status codes (200, 404, etc.) and response headers (Content-Type, Set-Cookie, etc.). Most importantly, it lets you obtain a PrintWriter with which you send the document content back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page. Form data, HTTP request headers, HTTP responses, and cookies are all discussed in the following sections.

Since doGet and doPost throw two exceptions, you are required to include them in the declaration. Finally, you must import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse).

A Servlet That Generates Plain Text

Listing 2.2 shows a simple servlet that outputs plain text, with the output shown in Figure 2–2. Before we move on, it is worth spending some time reviewing the process of installing, compiling, and running this simple servlet. See Chapter 1 (Server Setup and Configuration) for a much more detailed description of the process.

Figure 2-2Figure 2–2 Result of HelloWorld servlet.

First, be sure that your server is set up properly as described in Section 1.4 (Test the Server) and that your CLASSPATH refers to the necessary three entries (the JAR file containing the javax.servlet classes, your development directory, and "."), as described in Section 1.6 (Set Up Your Development Environment).

Second, type "javac HelloWorld.java" or tell your development environment to compile the servlet (e.g., by clicking Build in your IDE or selecting Compile from the emacs JDE menu). This will compile your servlet to create HelloWorld.class.

Third, move HelloWorld.class to the directory that your server uses to store servlets (usually install_dir/.../WEB-INF/classes—see Section 1.7). Alternatively, you can use one of the techniques of Section 1.8 (Establish a Simplified Deployment Method) to automatically place the class files in the appropriate location.

Finally, invoke your servlet. This last step involves using either the default URL of http://host/servlet/ServletName or a custom URL defined in the web.xml file as described in Section 5.3 (Assigning Names and Custom URLs). Figure 2–2 shows the servlet being accessed by means of the default URL, with the server running on the local machine.

Listing 2.2 HelloWorld.java

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

public class HelloWorld extends HttpServlet {
 public void doGet(HttpServletRequest request,
          HttpServletResponse response)
   throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  out.println("Hello World");
 }
}

A Servlet That Generates HTML

Most servlets generate HTML, not plain text as in the previous example. To build HTML, you need two additional steps:

  1. Tell the browser that you're sending back HTML.

  2. Modify the println statements to build a legal Web page.

You accomplish the first step by setting the HTTP Content-Type response header. In general, headers are set by the setHeader method of HttpServletResponse, but setting the content type is such a common task that there is also a special setContentType method just for this purpose. The way to designate HTML is with a type of text/html, so the code would look like this:

response.setContentType("text/html");

Although HTML is the most common type of document that servlets create, it is not unusual for servlets to create other document types. For example, it is quite common to use servlets to generate GIF images (content type image/gif) and Excel spreadsheets (content type application/vnd.ms-excel).

Don't be concerned if you are not yet familiar with HTTP response headers; they are discussed in Section 2.8. Note that you need to set response headers before actually returning any of the content with the PrintWriter. That's because an HTTP response consists of the status line, one or more headers, a blank line, and the actual document, in that order. The headers can appear in any order, and servlets buffer the headers and send them all at once, so it is legal to set the status code (part of the first line returned) even after setting headers. But servlets do not necessarily buffer the document itself, since users might want to see partial results for long pages. Servlet engines are permitted to partially buffer the output, but the size of the buffer is left unspecified. You can use the getBufferSize method of HttpServletResponse to determine the size, or you can use setBufferSize to specify it. You can set headers until the buffer fills up and is actually sent to the client. If you aren't sure whether the buffer has been sent, you can use the isCommitted method to check. Even so, the simplest approach is to simply put the setContentType line before any of the lines that use the PrintWriter.

Core Approach

Always set the content type before transmitting the actual document.

The second step in writing a servlet that builds an HTML document is to have your println statements output HTML, not plain text. Listing 2.3 shows HelloServlet.java, the sample servlet used in Section 1.7 to verify that the server is functioning properly. As Figure 2–3 illustrates, the browser formats the result as HTML, not as plain text.

Listing 2.3 HelloServlet.java

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

public class HelloServlet extends HttpServlet {
 public void doGet(HttpServletRequest request,
          HttpServletResponse response)
   throws ServletException, IOException {
response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  String docType =
   "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
   "Transitional//EN\">\n";
  out.println(docType +
        "<HTML>\n" +
        "<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
        "<BODY BGCOLOR=\"#FDF5E6\">\n" +
        "<H1>Hello</H1>\n" +
        "</BODY></HTML>");
 }
}

Figure 2-3Figure 2–3 Result of HelloServlet.

Servlet Packaging

In a production environment, multiple programmers can be developing servlets for the same server. So, placing all the servlets in the same directory results in a massive, hard-to-manage collection of classes and risks name conflicts when two developers accidentally choose the same servlet name. Packages are the natural solution to this problem. As we'll see in Chapter 4, even the use of Web applications does not obviate the need for packages.

When you use packages, you need to perform the following two additional steps.

  1. Move the files to a subdirectory that matches the intended package name. For example, I'll use the moreservlets package for most of the rest of the servlets in this book. So, the class files need to go in a subdirectory called moreservlets.

  2. Insert a package statement in the class file. For example, to place a class in a package called somePackage, the class should be in the somePackage directory and the first non-comment line of the file should read

package somePackage;

For example, Listing 2.4 presents a variation of HelloServlet that is in the moreservlets package and thus the moreservlets directory. As discussed in Section 1.7 (Compile and Test Some Simple Servlets), the class file should be placed in install_dir/webapps/ROOT/WEB-INF/classes/moreservlets for Tomcat, in install_dir/servers/default/default-app/WEB-INF/classes/moreservlets for JRun, and in install_dir/Servlets/moreservlets for ServletExec.

Figure 2–4 shows the servlet accessed by means of the default URL.

Listing 2.4 HelloServlet2.java

package moreservlets;

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

/** Simple servlet used to test the use of packages. */

public class HelloServlet2 extends HttpServlet {
 public void doGet(HttpServletRequest request,
          HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  String docType =
   "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
   "Transitional//EN\">\n";
  out.println(docType +
        "<HTML>\n" +
        "<HEAD><TITLE>Hello (2)</TITLE></HEAD>\n" +
        "<BODY BGCOLOR=\"#FDF5E6\">\n" +
        "<H1>Hello (2)</H1>\n" +
        "</BODY></HTML>");
 }
}

Figure 2-4Figure 2–4 Result of HelloServlet2.

Simple HTML-Building Utilities

As you probably already know, an HTML document is structured as follows:

<!DOCTYPE ...>
<HTML>
<HEAD><TITLE>...</TITLE>...</HEAD>
<BODY ...>...</BODY>
</HTML>

When using servlets to build the HTML, you might be tempted to omit part of this structure, especially the DOCTYPE line, noting that virtually all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. I strongly discourage this practice. The advantage of the DOC_TYPE line is that it tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors that your browser guesses well on but that other browsers will have trouble displaying.

The two most popular online validators are the ones from the World Wide Web Consortium (http://validator.w3.org/) and from the Web Design Group (http://www.htmlhelp.com/tools/validator/). They let you submit a URL, then they retrieve the page, check the syntax against the formal HTML specification, and report any errors to you. Since, to a visitor, a servlet that generates HTML looks exactly like a regular Web page, it can be validated in the normal manner unless it requires POST data to return its result. Since GET data is attached to the URL, you can even send the validators a URL that includes GET data. If the servlet is available only inside your corporate firewall, simply run it, save the HTML to disk, and choose the validator's File Upload option.

Core Approach

Use an HTML validator to check the syntax of pages that your servlets generate.

Admittedly, it is a bit cumbersome to generate HTML with println statements, especially long tedious lines like the DOCTYPE declaration. Some people address this problem by writing detailed HTML-generation utilities, then use the utilities throughout their servlets. I'm skeptical of the usefulness of such an extensive library. First and foremost, the inconvenience of generating HTML programmatically is one of the main problems addressed by JavaServer Pages. Second, HTML generation routines can be cumbersome and tend not to support the full range of HTML attributes (CLASS and ID for style sheets, JavaScript event handlers, table cell background colors, and so forth).

Despite the questionable value of a full-blown HTML generation library, if you find you're repeating the same constructs many times, you might as well create a simple utility file that simplifies those constructs. For standard servlets, two parts of the Web page (DOCTYPE and HEAD) are unlikely to change and thus could benefit from being incorporated into a simple utility file. These are shown in Listing 2.5, with Listing 2.6 showing a variation of HelloServlet that makes use of this utility. I'll add a few more utilities throughout the chapter.

Listing 2.5 moreservlets/ServletUtilities.java

package moreservlets; 

import javax.servlet.*;
import javax.servlet.http.*;

/** Some simple time savers. Note that most are static methods. */

public class ServletUtilities {
 public static final String DOCTYPE =
  "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
  "Transitional//EN\">";

 public static String headWithTitle(String title) {
  return(DOCTYPE + "\n" +
      "<HTML>\n" +
      "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
 }

 ...
}

Listing 2.6 moreservlets/HelloServlet3.java

package moreservlets;

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

/** Simple servlet used to test the use of packages
 * and utilities from the same package.
 */

public class HelloServlet3 extends HttpServlet {
 public void doGet(HttpServletRequest request,
          HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  String title = "Hello (3)";
  out.println(ServletUtilities.headWithTitle(title) + 
        "<BODY BGCOLOR=\"#FDF5E6\">\n" +
        "<H1>" + title + "</H1>\n" +
        "</BODY></HTML>");
 }
}

After you compile HelloServlet3.java (which results in ServletUtilities.java being compiled automatically), you need to move the two class files to the moreservlets subdirectory of the server's default deployment location. If you get an "Unresolved symbol" error when compiling HelloServlet3.java, go back and review the CLASSPATH settings described in Section 1.6 (Set Up Your Development Environment). If you don't know where to put the class files, review Sections 1.7 and 1.9. Figure 2–5 shows the result when the servlet is invoked with the default URL.

Figure 2-5Figure 2–5 Result of HelloServlet3.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020