Tag Archives: Servlet

ShowCookies.java Servlet that displays all cookies that arrived in current request. Uses the ServletUtilities class.

Huge Sell on Popular Electronics

ShowCookies.java  Servlet that displays all cookies that arrived in current request. Uses the ServletUtilities  class. 

package cwp;

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

/** Sets six cookies: three that apply only to the current
 *  session (regardless of how long that session lasts)
 *  and three that persist for an hour (regardless of
 *  whether the browser is restarted).
 *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class SetCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for an hour, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge(3600); response.addCookie(cookie); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies"; out.println (ServletUtilities.headWithTitle(title) + "\n" + "

" + title + "

\n" +
       "There are six cookies associated with this page.\n" +
       "To see them, visit the\n" +
       "\n" +
       "ShowCookies servlet.\n" +
       "

\n" + "Three of the cookies are associated only with the\n" + "current session, while three are persistent.\n" + "Quit the browser, restart, and return to the\n" + "ShowCookies servlet to verify that\n" + "the three long-lived ones persist across sessions.\n" + ""); } } ServletUtilities.java package cwp; import javax.servlet.*; import javax.servlet.http.*; /** Some simple time savers. Note that most are static methods. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ServletUtilities { public static final String DOCTYPE = ""; public static String headWithTitle(String title) { return(DOCTYPE + "\n" + "\n" + "\n"); } /** Read a parameter with the specified name, convert it * to an int, and return it. Return the designated default * value if the parameter doesn't exist or if it is an * illegal integer format. */ public static int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) { String paramString = request.getParameter(paramName); int paramValue; try { paramValue = Integer.parseInt(paramString); } catch(NumberFormatException nfe) { // null or bad format paramValue = defaultValue; } return(paramValue); } /** Given an array of Cookies, a name, and a default value, * this method tries to find the value of the cookie with * the given name. If there is no cookie matching the name * in the array, then the default value is returned instead. */ public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) { if (cookies != null) { for(int i=0; i<cookies.length; i++)="" {="" cookie="" if="" (cookiename.equals(cookie.getname()))="" return(cookie.getvalue());="" }="" return(defaultvalue);="" **="" given="" an="" array="" of="" cookies="" and="" a="" name,="" this="" method="" tries="" *="" to="" find="" return="" the="" from="" that="" has="" name.="" there="" is="" no="" matching="" name="" in="" array,="" null="" returned.="" public="" static="" getcookie(cookie[]="" cookies,="" string="" cookiename)="" (cookies="" !="null)" for(int="" i="0;" i<cookies.length;="" return(cookie);="" return(null);="" string,="" replaces="" all="" occurrences="" '<'="" with="" '<',="" '="">' with * '>', and (to handle cases that occur inside attribute * values), all occurrences of double quotes with * '"' and all occurrences of '&' with '&'. * Without such filtering, an arbitrary string * could not safely be inserted in a Web page. */ public static String filter(String input) { StringBuffer filtered = new StringBuffer(input.length()); char c; for(int i=0; i<input.length(); i++)="" {="" c="input.charAt(i);" if="" (c="=" '<')="" filtered.append("<");="" }="" else="" '="">') { filtered.append(">"); } else if (c == '"') { filtered.append("""); } else if (c == '&') { filtered.append("&"); } else { filtered.append(c); } } return(filtered.toString()); } }

SearchEngines.java Servlet that redirects requests to various search engines. Uses the SearchSpec helper class. Accessed by means of SearchEngines.html.

Huge Sell on Popular Electronics

SearchEngines.java  Servlet that redirects requests to various search engines. Uses the SearchSpec  helper class. Accessed by means of SearchEngines.html. 

package cwp;

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

/** Servlet that takes a search string, number of results per
 *  page, and a search engine name, sending the query to
 *  that search engine. Illustrates manipulating
 *  the response status line. It sends a 302 response
 *  (via sendRedirect) if it gets a known search engine,
 *  and sends a 404 response (via sendError) otherwise.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SearchEngines extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    String searchString = request.getParameter("searchString");
    if ((searchString == null) ||
        (searchString.length() == 0)) {
      reportProblem(response, "Missing search string.");
      return;
    }
    // The URLEncoder changes spaces to "+" signs and other
    // non-alphanumeric characters to "%XY", where XY is the
    // hex value of the ASCII (or ISO Latin-1) character.
    // Browsers always URL-encode form values, so the
    // getParameter method decodes automatically. But since
    // we're just passing this on to another server, we need to
    // re-encode it.
    searchString = URLEncoder.encode(searchString);
    String numResults = request.getParameter("numResults");
    if ((numResults == null) ||
        (numResults.equals("0")) ||
        (numResults.length() == 0)) {
      numResults = "10";
    }
    String searchEngine =
      request.getParameter("searchEngine");
    if (searchEngine == null) {
      reportProblem(response, "Missing search engine name.");
      return;
    }
    SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs();
    for(int i=0; i" + message + "");
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}



SearchSpec.java

package cwp;

/** Small class that encapsulates how to construct a
 *  search string for a particular search engine.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  May be freely used or adapted.
 */

public class SearchSpec {
  private String name, baseURL, numResultsSuffix;

  private static SearchSpec[] commonSpecs =
    { new SearchSpec("google",
                     "http://www.google.com/search?q=",
                     "&num="),
      new SearchSpec("infoseek",
                     "http://infoseek.go.com/Titles?qt=",
                     "&nh="),
      new SearchSpec("lycos",
                     "http://lycospro.lycos.com/cgi-bin/" +
                        "pursuit?query=",
                     "&maxhits="),
      new SearchSpec("hotbot",
                     "http://www.hotbot.com/?MT=",
                     "&DC=")
    };

  public SearchSpec(String name,
                    String baseURL,
                    String numResultsSuffix) {
    this.name = name;
    this.baseURL = baseURL;
    this.numResultsSuffix = numResultsSuffix;
  }

  public String makeURL(String searchString,
                        String numResults) {
    return(baseURL + searchString +
           numResultsSuffix + numResults);
  }

  public String getName() {
    return(name);
  }

  public static SearchSpec[] getCommonSpecs() {
    return(commonSpecs);
  }
}

SetCookies.java Servlet that sets a few persistent and session cookies. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output.

Huge Sell on Popular Electronics

SetCookies.java  Servlet that sets a few persistent and session cookies. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output.

 

package cwp;

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

/** Sets six cookies: three that apply only to the current
 *  session (regardless of how long that session lasts)
 *  and three that persist for an hour (regardless of
 *  whether the browser is restarted).
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SetCookies extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    for(int i=0; i<3; i++) {
      // Default maxAge is -1, indicating cookie
      // applies only to current browsing session.
      Cookie cookie = new Cookie("Session-Cookie-" + i,
                                 "Cookie-Value-S" + i);
      response.addCookie(cookie);
      cookie = new Cookie("Persistent-Cookie-" + i,
                          "Cookie-Value-P" + i);
      // Cookie is valid for an hour, regardless of whether
      // user quits browser, reboots computer, or whatever.
      cookie.setMaxAge(3600);
      response.addCookie(cookie);
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Setting Cookies";
    out.println
      (ServletUtilities.headWithTitle(title) +
       "\n" +
       "
" + title + "
\n" +
       "There are six cookies associated with this page.\n" +
       "To see them, visit the\n" +
       "\n" +
       "ShowCookies servlet.\n" +
       "

\n" +
       "Three of the cookies are associated only with the\n" +
       "current session, while three are persistent.\n" +
       "Quit the browser, restart, and return to the\n" +
       "ShowCookies servlet to verify that\n" +
       "the three long-lived ones persist across sessions.\n" +
       "");
  }
}



ServletUtilities.java

package cwp;

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

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


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

EncodedPage.java Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output.

Huge Sell on Popular Electronics

EncodedPage.java  Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output. 

package cwp;

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

/** Example showing benefits of gzipping pages to browsers
 *  that can handle gzip.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class EncodedPage extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    String encodings = request.getHeader("Accept-Encoding");
    String encodeFlag = request.getParameter("encoding");
    PrintWriter out;
    String title;
    if ((encodings != null) &&
        (encodings.indexOf("gzip") != -1) &&
        !"none".equals(encodeFlag)) {
      title = "Page Encoded with GZip";
      OutputStream out1 = response.getOutputStream();
      out = new PrintWriter(new GZIPOutputStream(out1), false);
      response.setHeader("Content-Encoding", "gzip");
    } else {
      title = "Unencoded Page";
      out = response.getWriter();
    }
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n");
    String line = "Blah, blah, blah, blah, blah. " +
                  "Yadda, yadda, yadda, yadda.";
    for(int i=0; i<10000; i++) {
      out.println(line);
    }
    out.println("");
    out.close();
  }
}

PrimeNumbers.java Servlet that processes a request to generate n prime numbers, each with at least m digits. If these results are not complete, it sends a Refresh header instructing the browser to ask for new results a little while later. Uses the Primes

Huge Sell on Popular Electronics

PrimeNumbers.java  Servlet that processes a request to generate n prime numbers, each with at least m digits. If these results are not complete, it sends a Refresh header instructing the browser to ask for new results a little while later. Uses the Primes, PrimeList, and ServletUtilities  classes.

 

package cwp;

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

/** Servlet that processes a request to generate n
 *  prime numbers, each with at least m digits.
 *  It performs the calculations in a low-priority background
 *  thread, returning only the results it has found so far.
 *  If these results are not complete, it sends a Refresh
 *  header instructing the browser to ask for new results a
 *  little while later. It also maintains a list of a
 *  small number of previously calculated prime lists
 *  to return immediately to anyone who supplies the
 *  same n and m as a recent completed computation.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class PrimeNumbers extends HttpServlet {
  private Vector primeListVector = new Vector();
  private int maxPrimeLists = 30;

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    int numPrimes =
      ServletUtilities.getIntParameter(request,
                                       "numPrimes", 50);
    int numDigits =
      ServletUtilities.getIntParameter(request,
                                       "numDigits", 120);
    PrimeList primeList =
      findPrimeList(primeListVector, numPrimes, numDigits);
    if (primeList == null) {
      primeList = new PrimeList(numPrimes, numDigits, true);
      // Multiple servlet request threads share the instance
      // variables (fields) of PrimeNumbers. So
      // synchronize all access to servlet fields.
      synchronized(primeListVector) {
        if (primeListVector.size() >= maxPrimeLists)
          primeListVector.removeElementAt(0);
        primeListVector.addElement(primeList);
      }
    }
    Vector currentPrimes = primeList.getPrimes();
    int numCurrentPrimes = currentPrimes.size();
    int numPrimesRemaining = (numPrimes - numCurrentPrimes);
    boolean isLastResult = (numPrimesRemaining == 0);
    if (!isLastResult) {
      response.setHeader("Refresh", "5");
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Some " + numDigits + "-Digit Prime Numbers";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n" +
                "
Primes found with " + numDigits +
                " or more digits: " + numCurrentPrimes +
                ".
");
    if (isLastResult)
      out.println("Done searching.");
    else
      out.println("Still looking for " + numPrimesRemaining +
                  " more...");
    out.println("

    ");
        for(int i=0; i" + currentPrimes.elementAt(i));
        }
        out.println("

");
    out.println("");
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  // See if there is an existing ongoing or completed
  // calculation with the same number of primes and number
  // of digits per prime. If so, return those results instead
  // of starting a new background thread. Keep this list
  // small so that the Web server doesn't use too much memory.
  // Synchronize access to the list since there may be
  // multiple simultaneous requests.

  private PrimeList findPrimeList(Vector primeListVector,
                                  int numPrimes,
                                  int numDigits) {
    synchronized(primeListVector) {
      for(int i=0; i
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class Primes {
  // Note that BigInteger.ZERO was new in JDK 1.2, and 1.1
  // code is being used to support the most servlet engines.
  private static final BigInteger ZERO = new BigInteger("0");
  private static final BigInteger ONE = new BigInteger("1");
  private static final BigInteger TWO = new BigInteger("2");

  // Likelihood of false prime is less than 1/2^ERR_VAL
  // Assumedly BigInteger uses the Miller-Rabin test or
  // equivalent, and thus is NOT fooled by Carmichael numbers.
  // See section 33.8 of Cormen et al's Introduction to
  // Algorithms for details.
  private static final int ERR_VAL = 100;

  public static BigInteger nextPrime(BigInteger start) {
    if (isEven(start))
      start = start.add(ONE);
    else
      start = start.add(TWO);
    if (start.isProbablePrime(ERR_VAL))
      return(start);
    else
      return(nextPrime(start));
  }

  private static boolean isEven(BigInteger n) {
    return(n.mod(TWO).equals(ZERO));
  }

  private static StringBuffer[] digits =
    { new StringBuffer("0"), new StringBuffer("1"),
      new StringBuffer("2"), new StringBuffer("3"),
      new StringBuffer("4"), new StringBuffer("5"),
      new StringBuffer("6"), new StringBuffer("7"),
      new StringBuffer("8"), new StringBuffer("9") };

  private static StringBuffer randomDigit() {
    int index = (int)Math.floor(Math.random() * 10);
    return(digits[index]);
  }

  public static BigInteger random(int numDigits) {
    StringBuffer s = new StringBuffer("");
    for(int i=0; i 0)
      numDigits = Integer.parseInt(args[0]);
    else
      numDigits = 150;
    BigInteger start = random(numDigits);
    for(int i=0; i<50; i++) {
      start = nextPrime(start);
      System.out.println("Prime " + i + " = " + start);
    }
  }
}



PrimeList.java
package cwp;

import java.util.*;
import java.math.BigInteger;

/** Creates a Vector of large prime numbers, usually in
 *  a low-priority background thread. Provides a few small
 *  thread-safe access methods.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class PrimeList implements Runnable {
  private Vector primesFound;
  private int numPrimes, numDigits;

  /** Finds numPrimes prime numbers, each of which are
   *  numDigits long or longer. You can set it to only
   *  return when done, or have it return immediately,
   *  and you can later poll it to see how far it
   *  has gotten.
   */

  public PrimeList(int numPrimes, int numDigits,
                   boolean runInBackground) {
    // Using Vector instead of ArrayList
    // to support JDK 1.1 servlet engines
    primesFound = new Vector(numPrimes);
    this.numPrimes = numPrimes;
    this.numDigits = numDigits;
    if (runInBackground) {
      Thread t = new Thread(this);
      // Use low priority so you don't slow down server.
      t.setPriority(Thread.MIN_PRIORITY);
      t.start();
    } else {
      run();
    }
  }

  public void run() {
    BigInteger start = Primes.random(numDigits);
    for(int i=0; i
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

ShowRequestHeaders.java Servlet that shows all request headers sent by browser in current request.

Huge Sell on Popular Electronics

ShowRequestHeaders.java  Servlet that shows all request headers sent by browser in current request. 

package cwp;

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

/** Shows all the request headers sent on this request.
 *
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ShowRequestHeaders extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Servlet Example: Showing Request Headers";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n" +
                "Request Method: " +
                request.getMethod() + "
\n" +
                "Request URI: " +
                request.getRequestURI() + "
\n" +
                "Request Protocol: " +
                request.getProtocol() + "

\n" +
                "\n" +
                "\n" +
                "
Header Name
Header Value");
    Enumeration headerNames = request.getHeaderNames();
    while(headerNames.hasMoreElements()) {
      String headerName = (String)headerNames.nextElement();
      out.println("
" + headerName);
      out.println("
" + request.getHeader(headerName));
    }
    out.println("
\n");
  }

  /** Let the same servlet handle both GET and POST. */

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}

ServletUtilities.java Utility class that, among other things, contains the static filter method that replaces special HTML characters with their HTML character entities.

Huge Sell on Popular Electronics

ServletUtilities.java  Utility class that, among other things, contains the static filter  method that replaces special HTML characters with their HTML character entities. 

package cwp;

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

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


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

ThreeParams.java Servlet that reads and displays three request (form) parameters. Uses the ServletUtilities class.

Huge Sell on Popular Electronics

ThreeParams.java  Servlet that reads and displays three request (form) parameters. Uses the ServletUtilities  class. 

package cwp;

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

/** Simple servlet that reads three parameters from the
 *  form data.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ThreeParams extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading Three Request Parameters";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n" +
                "

    \n" +
                    "  
    param1: "
                    + request.getParameter("param1") + "\n" +
                    "  
    param2: "
                    + request.getParameter("param2") + "\n" +
                    "  
    param3: "
                    + request.getParameter("param3") + "\n" +
                    "

\n" +
                "");
  }
}

ShowMessage.java Servlet that demonstrates the use of initialization parameters.

Huge Sell on Popular Electronics

ShowMessage.java  Servlet that demonstrates the use of initialization parameters. Remember that, to use this servlet, you have to do three things:

    * Put the modified web.xml file in the WEB-INF directory.
    * Restart the server.
    * Use the registered servlet name (i.e., the URL http://host/servlet/ShowMsg), not the raw servlet name (i.e., the URL http://host/servlet/cwp.ShowMessage). 


package cwp;

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

/** Example using servlet initialization. Here, the message
 *  to print and the number of times the message should be
 *  repeated is taken from the init parameters.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ShowMessage extends HttpServlet {
  private String message;
  private String defaultMessage = "No message.";
  private int repeats = 1;

  public void init() throws ServletException {
    ServletConfig config = getServletConfig();
    message = config.getInitParameter("message");
    if (message == null) {
      message = defaultMessage;
    }
    try {
      String repeatString = config.getInitParameter("repeats");
      repeats = Integer.parseInt(repeatString);
    } catch(NumberFormatException nfe) {
      // NumberFormatException handles case where repeatString
      // is null *and* case where it is in an illegal format.
    }
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "The ShowMessage Servlet";
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
");
    for(int i=0; i" + message + "
");
    }
    out.println("");
  }
}


web.xml



?

ShowMsg
cwp.ShowMessage
?

message
Shibboleth

?

repeats
5


ServletUtilities.java Utility class that simplifies the output of the DOCTYPE and HEAD in servlets, among other things. Used by most remaining servlets in the chapter.

Huge Sell on Popular Electronics

ServletUtilities.java  Utility class that simplifies the output of the DOCTYPE and HEAD  in servlets, among other things. Used by most remaining servlets in the chapter. 

package cwp;

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

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


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */

  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */

  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}


SimplerHelloWWW.java Servlet that uses ServletUtilities to simplify the generation of the DOCTYPE and HEAD part of the servlet.

Huge Sell on Popular Electronics

SimplerHelloWWW.java  Servlet that uses ServletUtilities  to simplify the generation of the DOCTYPE and HEAD part of the servlet.

package cwp;

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

/** Simple servlet that generates HTML. This variation of
 *  HelloWWW uses the ServletUtilities utility class
 *  to generate the DOCTYPE, HEAD, and TITLE.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SimplerHelloWWW extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(ServletUtilities.headWithTitle("Hello WWW") +
                "\n" +
                "
Hello WWW
\n" +
                "");
  }
}


Servlet Utilities

package cwp;

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

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


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  May be freely used or adapted.
 */

public class ServletUtilities {
  public static final String DOCTYPE =
    "";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "\n" +
           "\n" +
           "\n");
  }

  /** Read a parameter with the specified name, convert it
   *  to an int, and return it. Return the designated default
   *  value if the parameter doesn't exist or if it is an
   *  illegal integer format.
  */
  
  public static int getIntParameter(HttpServletRequest request,
                                    String paramName,
                                    int defaultValue) {
    String paramString = request.getParameter(paramName);
    int paramValue;
    try {
      paramValue = Integer.parseInt(paramString);
    } catch(NumberFormatException nfe) { // null or bad format
      paramValue = defaultValue;
    }
    return(paramValue);
  }

  /** Given an array of Cookies, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If there is no cookie matching the name
   *  in the array, then the default value is returned instead.
   */
  
  public static String getCookieValue(Cookie[] cookies,
                                      String cookieName,
                                      String defaultValue) {
    if (cookies != null) {
      for(int i=0; i' with
   *  '>', and (to handle cases that occur inside attribute
   *  values), all occurrences of double quotes with
   *  '"' and all occurrences of '&' with '&'.
   *  Without such filtering, an arbitrary string
   *  could not safely be inserted in a Web page.
   */

  public static String filter(String input) {
    StringBuffer filtered = new StringBuffer(input.length());
    char c;
    for(int i=0; i') {
        filtered.append(">");
      } else if (c == '"') {
        filtered.append(""");
      } else if (c == '&') {
        filtered.append("&");
      } else {
        filtered.append(c);
      }
    }
    return(filtered.toString());
  }
}

HelloWWW.java Servlet that generates HTML. This and all remaining servlets are in the cwp package and therefore should be installed in the cwp subdirectory.

Huge Sell on Popular Electronics

HelloWWW.java  Servlet that generates HTML. This and all remaining servlets are in the cwp package and therefore should be installed in the cwp subdirectory.

package cwp;

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

/** Simple servlet that generates HTML.
 *  
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class HelloWWW extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
      "\n";
    out.println(docType +
                "\n" +
                "\n" +
                "\n" +
                "