Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Looking at an Example Servlet

Servlets are conceptually simple. You configure your Web server to map a certain URL path to a Java class (different servers do this differently). The Java class needs to extend HttpServlet and handle one of several methods: doGet, doPost, doPut, or doDelete. (doGet or doPost are used most commonly.)

These messages reflect the various ways that servlets are invoked by a GET, POST, PUT, or DELETE HTTP request from a client (although DELETE is rare). The servlet is responsible for setting the mime type, error code, cookies, and other status information about the request, as well as returning the content.

Let's say that the path /baseballstats has been mapped to the class BaseBallStatServlet. This is a class that knows about the current batting averages of major league baseball players. To use it, you send a URL like this:

http://www.baseballstats.com/baseballstats?player=Nomar Garciapara

Listing 3.1 is a simple implementation of that servlet.

Listing 3.1 BaseBallStatServlet.ava

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

public class BaseBallStatServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
  throws java.io.IOException {
  resp.setContentType("text/html");
  java.io.PrintWriter html = resp.getWriter();

  String player = (String) req.getParameter("player");

  html.println("<HTML><HEAD><TITLE>MLB Player Stats</TITLE></HEAD>");
  html.println("<BODY>");

  if ((player == null) || (player.length() == 0)) {
    html.println("<H1>No Player Requested</H1>");
  } else {
    if (player.equals("Nomar Garciapara")) {
    html.println("<H1>Nomar is batting .932</H1>");
    } else {
    html.println("<H1>" + player + " is batting .234</H1>");
    }
  }
  html.println("</BODY></HTML>");
  }
}

Ignoring for the moment the bias toward a certain Boston slugger, you can see that all the basic elements of a servlet are in place.

The doGet method is handed the request and response objects. The request has all the parameters handed in to the Web request, including cookies, form submissions, and header data. The response is used to formulate a reply to request.

To create the reply, the first thing you need to do is to set the content type of the reply. In most cases, that will be text/html, although you might be generating other types of replies, such as XML.

Next, you need to get a handle on the output stream so that you can start generating HTML. In cases in which you are writing text data (as opposed to binary data, such as if you were programmatically generating a JPG file), you want to get a PrintWriter, which you can find by calling getWriter on the response object.

Next you use getParameter on the request to get the form or URL submitted player name. You need to make sure to check for blank or null values for this parameter, or an exception might occur later.

Output the boilerplate HTML header for the document, then compare the name of the player against your primitive database, close the HTML forms, and you're finished with the request.

JSP: Servlets, Only Better!

Although we'll spend the rest of the chapter discussing the servlet objects because JSP uses them heavily, I'm going to say right here and now that using servlets themselves is not something I'd recommend.

This is because they obscure the functionality of the site and require ugly embedding of HTML inside Java. One of the features of JSP is that the formatting (HTML) has been largely segregated from the coding (Java). When you start using pure servlets, you have to put HTML code right in the middle of the Java.

As a result, you need to recompile the class every time you change a minor page format feature. This gets very exhausting very quickly during development, and it is worse in a deployed site.

Also, because of the indirection between the URL and the class name, you can have a difficult time trying to find the actual code behind a servlet request. It usually involves looking at the server configuration file, which can be confusing.

More to the point, everything that a servlet does can be done with a JSP page. Listings 3.2 and 3.3 show a JSP page and a Bean that do the same thing. Notice how much more clearly JSP does it in Listing 3.2.

Listing 3.2 BaseBallStats.jsp

<jsp:useBean id="statEngine" scope="session" class="com.mlb.stats.statBean" />
<HTML><HEAD><TITLE>MLB Player Stats</TITLE></HEAD>
<BODY>
<H1><%= statEngine.processRequest(request, response) %> </H1>
</BODY>
</HTML>

Listing 3.3 statBean.java

package com.mlb.stats;

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

public class statBean {
  public String processRequest(HttpServletRequest req, 
         HttpServletResponse resp) {

  String player = (String) req.getParameter("player");
  if ((player == null) || (player.length() == 0)) {
    return("No Player Requested");
  } else {
    if (player.equals("Nomar Garciapara")) {
    return("Nomar is batting .932");
    } else {
    return(player + " is batting .234");
    }
  }
  }
}

This is a much more desirable division of labor, with the JSP handling the HTML formatting and the back-end Java Bean handling the business logic. A third way (and the official JSP way) to write this is using jsp:setProperties to handle the form submit instead of letting the Bean decode the form arguments.

Servlet Functionality Inside JSP

If servlet programming is yesterday's news, why is a chapter devoted to it? The reason is that there's a lot of useful functionality in the Servlet API to take advantage of.

The previous code highlights one example—sometimes you want to explicitly handle a form submission rather than use the Bean property-setting mechanisms. This might be because you want to do a certain type of error checking (more on this in Chapter 8, "Retrieving, Storing, and Verifying User Input") or because you want to set values in a manner that's more complicated than the useProperty mechanism allows.

Beyond the getParameter functionality, there are a lot of other things that the various servlet classes can tell you. Let's break them down class by class.

HttpServletRequest

The HttpServletRequest object, which is available as request in a JSP page, contains all the information that is passed from the browser to the server during a Web transaction. The following code highlights a few of the things that can be extracted.

First, you'll extend the user object with another property:

  protected String userName;

  public String getUserName() {
  return userName;
  }

  public void setUserName(String uname) {
  userName = uname;
  }

Listing 3.4 gives the actual JSP code.

Listing 3.4 HttpObjectDemo.jsp

<jsp:useBean id="user" scope="session" class="com.cartapp.user.User" />
<jsp:setProperty name="user" property="*" />
<HTML>
<HEAD>
<TITLE>HttpRequest/HttpResponse Demo</TITLE>
</HEAD>
<BODY>
  <% 
Cookie [] cookies = request.getCookies();
boolean found_cookie = false;

if (cookies != null) {
  for (int i = 0; i < cookies.length; i++) {
  if (cookies[i].getName().equals("cartAppUserName")) {
    user.setUserName(cookies[i].getValue());
    found_cookie = true;
  }
  }
}
if (!found_cookie) {
  if (user.getUserName() != null) {
  Cookie setCookie = new Cookie("cartAppUserName", user.getUserName());
  setCookie.setMaxAge(3600 * 24 * 265); // Expire in one year
  response.addCookie(setCookie);
  found_cookie = true;
  }
}
if (!found_cookie) {
  %>
<FORM METHOD="POST">
Please Enter Your User Name: <INPUT TYPE="TEXT" NAME="userName"><BR>
<INPUT TYPE="SUBMIT">
</FORM>
<% } else { %>
<H1>Hello <%= user.getUserName() %></H1>
   <% 
   if (request.getAuthType() != null) {
   %> You don't need to use a secure connection.<p> <%
   } 
   %>
   For your information, your session id is <%= request.getRequestedSessionId() %><p>
   You accessed this page using a <%= request.getMethod() %><p>

   <%
   if (request.isRequestedSessionIdFromURL()) { %>
      You know, using URL rewriting is ugly, turn on cookie support.<p>
   <% } else { %>
      Good, you support cookies, nice choice.<p>
   <% }
 } %>
</BODY>
</HTML>

The first time you run this code, you'll see the page shown in Figure 3.1.

Figure 3.1 Running the servlet example for the first time.

If you fill in a value for the username and hit submit, you'll see the page shown in Figure 3.2.

Figure 3.2 Running the servlet example for the second time.

Let's go through the code and see what's going on. The first two lines of JSP should look familiar. They do the same importation and property setting of the User class as you've done before. When you first access the page, there are no parameters passed in, so the setProperty does nothing.

Next, the request object is queried for a list of all the cookies handed in with the request. When you request a Web page, the browser checks to see if any of the cookies that it has stored locally are applicable to the Web site being accessed. Usually, the cookie is stored so that any Web site under the top-level domain will be sent the cookie—which means, for example, that www1.mysite.com and www2.mysite.com can both see the cookie (assuming that you own a domain called mysite.com to begin with).

The code then iterates over the array of cookies looking for the cookie that holds the username of the user. If the code finds a match, it writes it into the Bean and sets a flag. In a real application, you probably also would make a database call to load all sorts of user information, as you'll see in Chapter 8.

If the code didn't find the cookie, it checks to see if the Bean's username is set. If it is, it means that the form has been submitted and that a username now resides inside the user object. If that is the case, the code adds a new cookie to the response object to set the username cookie to the submitted value with a one-year expiration.

If the cookie wasn't found, and it wasn't being written for the first time because of a form submit, it displays a form to let the user input one from a form. When the user hits Submit, he is brought back around to this page, but now setProperty places the submitted username into the user Bean. This means that when the code comes along that checks if there's a username present in the Bean, it will be true and the cookie will be set.

If a cookie was found, a check is made to see if a secure SSL request was used, which would be overkill for this application. Next, the user is shown his session ID, which is a unique ID code generated for each session to distinguish incoming requests. Then the user is told whether a GET, POST, or PUT was used to access this page.

The session ID is usually stored as a transient cookie (one with a MaxAge of -1, which means that it goes away when the browser is closed). If the user has disabled cookies, the session ID is passed around using URL rewriting. If that's happening, the user is sent a message telling him to be less paranoid and to turn cookies back on.

What you've just seen is essentially the code that every site that implements "remembering" your username goes through. Consider it your first peek at the process of making a customer-friendly Web site work.

The HttpServletResponse Object

You saw one thing that you can do with the response object in the last section—use it to set a cookie.

Listing 3.5 is a simple JSP page that demonstrates a number of neat things that you can do with the response object.

Listing 3.5 HttpResponseDemo.jsp

<% 
String arg = "default";
if (request.getParameter("arg") != null) {
  arg = request.getParameter("arg");
}

if (arg.equals("redirect")) {
  response.sendRedirect("http://www.cnn.com/");
} else if (arg.equals("xml")) {
  response.setContentType("text/xml");
%>
<Vegetable>
 <Name>Carrot</Name>
 <Color>Orange</Color>
 <Consumer>Bugs Bunny</Consumer>
</Vegetable>
<% 
   } else {
  response.sendError(HttpServletResponse.SC_NOT_FOUND, 
        "There's No Such Page!");
   }
%>

If you request the page with no arguments in the URL, you get an error message (see Figure 3.3).

This is an example of using the sendError method of the response object, which lets you generate an arbitrary status response for the request. In this case, we're generating a 404, file not found, although with a customized message rather than the generic Tomcat error message for a 404.

If you pass in arg=redirect on the URL, you get redirected to the CNN Web page. There are some specific restrictions on using redirect. The main restriction is that you have to make sure that the redirect is requested before any content is sent to the browser; otherwise, the redirect string shows up as text in the Web page.

If you use arg=xml, you're sent back some XML content. This demonstrates an important point—JSP and Java servlets can return more than just HTML content. By using the setContentType message, you can generate a response of any content type you want. For example, you could generate a JPG image using one of the Java image-manipulation libraries and send it back by setting the content type to image/jpeg (see Figure 3.4).

Figure 3.3 Using the sendError method.

Figure 3.4 Sending XML by setting the content type.

  • + Share This
  • 🔖 Save To Your Account

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